1 //===--- Format.cpp - Format C++ code -------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief This file implements functions declared in Format.h. This will be 12 /// split into separate files as we go. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/Format/Format.h" 17 #include "AffectedRangeManager.h" 18 #include "ContinuationIndenter.h" 19 #include "FormatInternal.h" 20 #include "FormatTokenLexer.h" 21 #include "NamespaceEndCommentsFixer.h" 22 #include "SortJavaScriptImports.h" 23 #include "TokenAnalyzer.h" 24 #include "TokenAnnotator.h" 25 #include "UnwrappedLineFormatter.h" 26 #include "UnwrappedLineParser.h" 27 #include "UsingDeclarationsSorter.h" 28 #include "WhitespaceManager.h" 29 #include "clang/Basic/Diagnostic.h" 30 #include "clang/Basic/DiagnosticOptions.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/VirtualFileSystem.h" 33 #include "clang/Lex/Lexer.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/Support/Allocator.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/Regex.h" 39 #include "llvm/Support/YAMLTraits.h" 40 #include <algorithm> 41 #include <memory> 42 #include <string> 43 44 #define DEBUG_TYPE "format-formatter" 45 46 using clang::format::FormatStyle; 47 48 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory) 49 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat) 50 51 namespace llvm { 52 namespace yaml { 53 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> { 54 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) { 55 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp); 56 IO.enumCase(Value, "Java", FormatStyle::LK_Java); 57 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript); 58 IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC); 59 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto); 60 IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen); 61 IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto); 62 } 63 }; 64 65 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> { 66 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) { 67 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); 68 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); 69 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11); 70 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); 71 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto); 72 } 73 }; 74 75 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> { 76 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) { 77 IO.enumCase(Value, "Never", FormatStyle::UT_Never); 78 IO.enumCase(Value, "false", FormatStyle::UT_Never); 79 IO.enumCase(Value, "Always", FormatStyle::UT_Always); 80 IO.enumCase(Value, "true", FormatStyle::UT_Always); 81 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation); 82 IO.enumCase(Value, "ForContinuationAndIndentation", 83 FormatStyle::UT_ForContinuationAndIndentation); 84 } 85 }; 86 87 template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> { 88 static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) { 89 IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave); 90 IO.enumCase(Value, "Single", FormatStyle::JSQS_Single); 91 IO.enumCase(Value, "Double", FormatStyle::JSQS_Double); 92 } 93 }; 94 95 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> { 96 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) { 97 IO.enumCase(Value, "None", FormatStyle::SFS_None); 98 IO.enumCase(Value, "false", FormatStyle::SFS_None); 99 IO.enumCase(Value, "All", FormatStyle::SFS_All); 100 IO.enumCase(Value, "true", FormatStyle::SFS_All); 101 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); 102 IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly); 103 IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty); 104 } 105 }; 106 107 template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> { 108 static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) { 109 IO.enumCase(Value, "All", FormatStyle::BOS_All); 110 IO.enumCase(Value, "true", FormatStyle::BOS_All); 111 IO.enumCase(Value, "None", FormatStyle::BOS_None); 112 IO.enumCase(Value, "false", FormatStyle::BOS_None); 113 IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment); 114 } 115 }; 116 117 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> { 118 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) { 119 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach); 120 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux); 121 IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla); 122 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup); 123 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman); 124 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU); 125 IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit); 126 IO.enumCase(Value, "Custom", FormatStyle::BS_Custom); 127 } 128 }; 129 130 template <> 131 struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> { 132 static void 133 enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) { 134 IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon); 135 IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma); 136 IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon); 137 } 138 }; 139 140 template <> 141 struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> { 142 static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) { 143 IO.enumCase(Value, "None", FormatStyle::PPDIS_None); 144 IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash); 145 } 146 }; 147 148 template <> 149 struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> { 150 static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) { 151 IO.enumCase(Value, "None", FormatStyle::RTBS_None); 152 IO.enumCase(Value, "All", FormatStyle::RTBS_All); 153 IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel); 154 IO.enumCase(Value, "TopLevelDefinitions", 155 FormatStyle::RTBS_TopLevelDefinitions); 156 IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions); 157 } 158 }; 159 160 template <> 161 struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> { 162 static void 163 enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) { 164 IO.enumCase(Value, "None", FormatStyle::DRTBS_None); 165 IO.enumCase(Value, "All", FormatStyle::DRTBS_All); 166 IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel); 167 168 // For backward compatibility. 169 IO.enumCase(Value, "false", FormatStyle::DRTBS_None); 170 IO.enumCase(Value, "true", FormatStyle::DRTBS_All); 171 } 172 }; 173 174 template <> 175 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> { 176 static void enumeration(IO &IO, 177 FormatStyle::NamespaceIndentationKind &Value) { 178 IO.enumCase(Value, "None", FormatStyle::NI_None); 179 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner); 180 IO.enumCase(Value, "All", FormatStyle::NI_All); 181 } 182 }; 183 184 template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> { 185 static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) { 186 IO.enumCase(Value, "Align", FormatStyle::BAS_Align); 187 IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign); 188 IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak); 189 190 // For backward compatibility. 191 IO.enumCase(Value, "true", FormatStyle::BAS_Align); 192 IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign); 193 } 194 }; 195 196 template <> 197 struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> { 198 static void enumeration(IO &IO, 199 FormatStyle::EscapedNewlineAlignmentStyle &Value) { 200 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign); 201 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left); 202 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right); 203 204 // For backward compatibility. 205 IO.enumCase(Value, "true", FormatStyle::ENAS_Left); 206 IO.enumCase(Value, "false", FormatStyle::ENAS_Right); 207 } 208 }; 209 210 template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> { 211 static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) { 212 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle); 213 IO.enumCase(Value, "Left", FormatStyle::PAS_Left); 214 IO.enumCase(Value, "Right", FormatStyle::PAS_Right); 215 216 // For backward compatibility. 217 IO.enumCase(Value, "true", FormatStyle::PAS_Left); 218 IO.enumCase(Value, "false", FormatStyle::PAS_Right); 219 } 220 }; 221 222 template <> 223 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> { 224 static void enumeration(IO &IO, 225 FormatStyle::SpaceBeforeParensOptions &Value) { 226 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never); 227 IO.enumCase(Value, "ControlStatements", 228 FormatStyle::SBPO_ControlStatements); 229 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always); 230 231 // For backward compatibility. 232 IO.enumCase(Value, "false", FormatStyle::SBPO_Never); 233 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements); 234 } 235 }; 236 237 template <> struct MappingTraits<FormatStyle> { 238 static void mapping(IO &IO, FormatStyle &Style) { 239 // When reading, read the language first, we need it for getPredefinedStyle. 240 IO.mapOptional("Language", Style.Language); 241 242 if (IO.outputting()) { 243 StringRef StylesArray[] = {"LLVM", "Google", "Chromium", 244 "Mozilla", "WebKit", "GNU"}; 245 ArrayRef<StringRef> Styles(StylesArray); 246 for (size_t i = 0, e = Styles.size(); i < e; ++i) { 247 StringRef StyleName(Styles[i]); 248 FormatStyle PredefinedStyle; 249 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) && 250 Style == PredefinedStyle) { 251 IO.mapOptional("# BasedOnStyle", StyleName); 252 break; 253 } 254 } 255 } else { 256 StringRef BasedOnStyle; 257 IO.mapOptional("BasedOnStyle", BasedOnStyle); 258 if (!BasedOnStyle.empty()) { 259 FormatStyle::LanguageKind OldLanguage = Style.Language; 260 FormatStyle::LanguageKind Language = 261 ((FormatStyle *)IO.getContext())->Language; 262 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) { 263 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle)); 264 return; 265 } 266 Style.Language = OldLanguage; 267 } 268 } 269 270 // For backward compatibility. 271 if (!IO.outputting()) { 272 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines); 273 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment); 274 IO.mapOptional("IndentFunctionDeclarationAfterType", 275 Style.IndentWrappedFunctionNames); 276 IO.mapOptional("PointerBindsToType", Style.PointerAlignment); 277 IO.mapOptional("SpaceAfterControlStatementKeyword", 278 Style.SpaceBeforeParens); 279 } 280 281 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); 282 IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket); 283 IO.mapOptional("AlignConsecutiveAssignments", 284 Style.AlignConsecutiveAssignments); 285 IO.mapOptional("AlignConsecutiveDeclarations", 286 Style.AlignConsecutiveDeclarations); 287 IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines); 288 IO.mapOptional("AlignOperands", Style.AlignOperands); 289 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); 290 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", 291 Style.AllowAllParametersOfDeclarationOnNextLine); 292 IO.mapOptional("AllowShortBlocksOnASingleLine", 293 Style.AllowShortBlocksOnASingleLine); 294 IO.mapOptional("AllowShortCaseLabelsOnASingleLine", 295 Style.AllowShortCaseLabelsOnASingleLine); 296 IO.mapOptional("AllowShortFunctionsOnASingleLine", 297 Style.AllowShortFunctionsOnASingleLine); 298 IO.mapOptional("AllowShortIfStatementsOnASingleLine", 299 Style.AllowShortIfStatementsOnASingleLine); 300 IO.mapOptional("AllowShortLoopsOnASingleLine", 301 Style.AllowShortLoopsOnASingleLine); 302 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType", 303 Style.AlwaysBreakAfterDefinitionReturnType); 304 IO.mapOptional("AlwaysBreakAfterReturnType", 305 Style.AlwaysBreakAfterReturnType); 306 // If AlwaysBreakAfterDefinitionReturnType was specified but 307 // AlwaysBreakAfterReturnType was not, initialize the latter from the 308 // former for backwards compatibility. 309 if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None && 310 Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) { 311 if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All) 312 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 313 else if (Style.AlwaysBreakAfterDefinitionReturnType == 314 FormatStyle::DRTBS_TopLevel) 315 Style.AlwaysBreakAfterReturnType = 316 FormatStyle::RTBS_TopLevelDefinitions; 317 } 318 319 IO.mapOptional("AlwaysBreakBeforeMultilineStrings", 320 Style.AlwaysBreakBeforeMultilineStrings); 321 IO.mapOptional("AlwaysBreakTemplateDeclarations", 322 Style.AlwaysBreakTemplateDeclarations); 323 IO.mapOptional("BinPackArguments", Style.BinPackArguments); 324 IO.mapOptional("BinPackParameters", Style.BinPackParameters); 325 IO.mapOptional("BraceWrapping", Style.BraceWrapping); 326 IO.mapOptional("BreakBeforeBinaryOperators", 327 Style.BreakBeforeBinaryOperators); 328 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces); 329 IO.mapOptional("BreakBeforeInheritanceComma", 330 Style.BreakBeforeInheritanceComma); 331 IO.mapOptional("BreakBeforeTernaryOperators", 332 Style.BreakBeforeTernaryOperators); 333 334 bool BreakConstructorInitializersBeforeComma = false; 335 IO.mapOptional("BreakConstructorInitializersBeforeComma", 336 BreakConstructorInitializersBeforeComma); 337 IO.mapOptional("BreakConstructorInitializers", 338 Style.BreakConstructorInitializers); 339 // If BreakConstructorInitializersBeforeComma was specified but 340 // BreakConstructorInitializers was not, initialize the latter from the 341 // former for backwards compatibility. 342 if (BreakConstructorInitializersBeforeComma && 343 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) 344 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 345 346 IO.mapOptional("BreakAfterJavaFieldAnnotations", 347 Style.BreakAfterJavaFieldAnnotations); 348 IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals); 349 IO.mapOptional("ColumnLimit", Style.ColumnLimit); 350 IO.mapOptional("CommentPragmas", Style.CommentPragmas); 351 IO.mapOptional("CompactNamespaces", Style.CompactNamespaces); 352 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", 353 Style.ConstructorInitializerAllOnOneLineOrOnePerLine); 354 IO.mapOptional("ConstructorInitializerIndentWidth", 355 Style.ConstructorInitializerIndentWidth); 356 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth); 357 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle); 358 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment); 359 IO.mapOptional("DisableFormat", Style.DisableFormat); 360 IO.mapOptional("ExperimentalAutoDetectBinPacking", 361 Style.ExperimentalAutoDetectBinPacking); 362 IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments); 363 IO.mapOptional("ForEachMacros", Style.ForEachMacros); 364 IO.mapOptional("IncludeBlocks", Style.IncludeBlocks); 365 IO.mapOptional("IncludeCategories", Style.IncludeCategories); 366 IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex); 367 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); 368 IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives); 369 IO.mapOptional("IndentWidth", Style.IndentWidth); 370 IO.mapOptional("IndentWrappedFunctionNames", 371 Style.IndentWrappedFunctionNames); 372 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes); 373 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports); 374 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks", 375 Style.KeepEmptyLinesAtTheStartOfBlocks); 376 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin); 377 IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd); 378 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); 379 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation); 380 IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth); 381 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); 382 IO.mapOptional("ObjCSpaceBeforeProtocolList", 383 Style.ObjCSpaceBeforeProtocolList); 384 IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment); 385 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter", 386 Style.PenaltyBreakBeforeFirstCallParameter); 387 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment); 388 IO.mapOptional("PenaltyBreakFirstLessLess", 389 Style.PenaltyBreakFirstLessLess); 390 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString); 391 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); 392 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", 393 Style.PenaltyReturnTypeOnItsOwnLine); 394 IO.mapOptional("PointerAlignment", Style.PointerAlignment); 395 IO.mapOptional("RawStringFormats", Style.RawStringFormats); 396 IO.mapOptional("ReflowComments", Style.ReflowComments); 397 IO.mapOptional("SortIncludes", Style.SortIncludes); 398 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations); 399 IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast); 400 IO.mapOptional("SpaceAfterTemplateKeyword", 401 Style.SpaceAfterTemplateKeyword); 402 IO.mapOptional("SpaceBeforeAssignmentOperators", 403 Style.SpaceBeforeAssignmentOperators); 404 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens); 405 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses); 406 IO.mapOptional("SpacesBeforeTrailingComments", 407 Style.SpacesBeforeTrailingComments); 408 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles); 409 IO.mapOptional("SpacesInContainerLiterals", 410 Style.SpacesInContainerLiterals); 411 IO.mapOptional("SpacesInCStyleCastParentheses", 412 Style.SpacesInCStyleCastParentheses); 413 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses); 414 IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets); 415 IO.mapOptional("Standard", Style.Standard); 416 IO.mapOptional("TabWidth", Style.TabWidth); 417 IO.mapOptional("UseTab", Style.UseTab); 418 } 419 }; 420 421 template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> { 422 static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) { 423 IO.mapOptional("AfterClass", Wrapping.AfterClass); 424 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement); 425 IO.mapOptional("AfterEnum", Wrapping.AfterEnum); 426 IO.mapOptional("AfterFunction", Wrapping.AfterFunction); 427 IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace); 428 IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration); 429 IO.mapOptional("AfterStruct", Wrapping.AfterStruct); 430 IO.mapOptional("AfterUnion", Wrapping.AfterUnion); 431 IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock); 432 IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch); 433 IO.mapOptional("BeforeElse", Wrapping.BeforeElse); 434 IO.mapOptional("IndentBraces", Wrapping.IndentBraces); 435 IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction); 436 IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord); 437 IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace); 438 } 439 }; 440 441 template <> struct MappingTraits<FormatStyle::IncludeCategory> { 442 static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) { 443 IO.mapOptional("Regex", Category.Regex); 444 IO.mapOptional("Priority", Category.Priority); 445 } 446 }; 447 448 template <> struct ScalarEnumerationTraits<FormatStyle::IncludeBlocksStyle> { 449 static void enumeration(IO &IO, FormatStyle::IncludeBlocksStyle &Value) { 450 IO.enumCase(Value, "Preserve", FormatStyle::IBS_Preserve); 451 IO.enumCase(Value, "Merge", FormatStyle::IBS_Merge); 452 IO.enumCase(Value, "Regroup", FormatStyle::IBS_Regroup); 453 } 454 }; 455 456 template <> struct MappingTraits<FormatStyle::RawStringFormat> { 457 static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) { 458 IO.mapOptional("Delimiter", Format.Delimiter); 459 IO.mapOptional("Language", Format.Language); 460 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle); 461 } 462 }; 463 464 // Allows to read vector<FormatStyle> while keeping default values. 465 // IO.getContext() should contain a pointer to the FormatStyle structure, that 466 // will be used to get default values for missing keys. 467 // If the first element has no Language specified, it will be treated as the 468 // default one for the following elements. 469 template <> struct DocumentListTraits<std::vector<FormatStyle>> { 470 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) { 471 return Seq.size(); 472 } 473 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq, 474 size_t Index) { 475 if (Index >= Seq.size()) { 476 assert(Index == Seq.size()); 477 FormatStyle Template; 478 if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) { 479 Template = Seq[0]; 480 } else { 481 Template = *((const FormatStyle *)IO.getContext()); 482 Template.Language = FormatStyle::LK_None; 483 } 484 Seq.resize(Index + 1, Template); 485 } 486 return Seq[Index]; 487 } 488 }; 489 } // namespace yaml 490 } // namespace llvm 491 492 namespace clang { 493 namespace format { 494 495 const std::error_category &getParseCategory() { 496 static ParseErrorCategory C; 497 return C; 498 } 499 std::error_code make_error_code(ParseError e) { 500 return std::error_code(static_cast<int>(e), getParseCategory()); 501 } 502 503 inline llvm::Error make_string_error(const llvm::Twine &Message) { 504 return llvm::make_error<llvm::StringError>(Message, 505 llvm::inconvertibleErrorCode()); 506 } 507 508 const char *ParseErrorCategory::name() const noexcept { 509 return "clang-format.parse_error"; 510 } 511 512 std::string ParseErrorCategory::message(int EV) const { 513 switch (static_cast<ParseError>(EV)) { 514 case ParseError::Success: 515 return "Success"; 516 case ParseError::Error: 517 return "Invalid argument"; 518 case ParseError::Unsuitable: 519 return "Unsuitable"; 520 } 521 llvm_unreachable("unexpected parse error"); 522 } 523 524 static FormatStyle expandPresets(const FormatStyle &Style) { 525 if (Style.BreakBeforeBraces == FormatStyle::BS_Custom) 526 return Style; 527 FormatStyle Expanded = Style; 528 Expanded.BraceWrapping = {false, false, false, false, false, 529 false, false, false, false, false, 530 false, false, true, true, true}; 531 switch (Style.BreakBeforeBraces) { 532 case FormatStyle::BS_Linux: 533 Expanded.BraceWrapping.AfterClass = true; 534 Expanded.BraceWrapping.AfterFunction = true; 535 Expanded.BraceWrapping.AfterNamespace = true; 536 break; 537 case FormatStyle::BS_Mozilla: 538 Expanded.BraceWrapping.AfterClass = true; 539 Expanded.BraceWrapping.AfterEnum = true; 540 Expanded.BraceWrapping.AfterFunction = true; 541 Expanded.BraceWrapping.AfterStruct = true; 542 Expanded.BraceWrapping.AfterUnion = true; 543 Expanded.BraceWrapping.AfterExternBlock = true; 544 Expanded.BraceWrapping.SplitEmptyFunction = true; 545 Expanded.BraceWrapping.SplitEmptyRecord = false; 546 break; 547 case FormatStyle::BS_Stroustrup: 548 Expanded.BraceWrapping.AfterFunction = true; 549 Expanded.BraceWrapping.BeforeCatch = true; 550 Expanded.BraceWrapping.BeforeElse = true; 551 break; 552 case FormatStyle::BS_Allman: 553 Expanded.BraceWrapping.AfterClass = true; 554 Expanded.BraceWrapping.AfterControlStatement = true; 555 Expanded.BraceWrapping.AfterEnum = true; 556 Expanded.BraceWrapping.AfterFunction = true; 557 Expanded.BraceWrapping.AfterNamespace = true; 558 Expanded.BraceWrapping.AfterObjCDeclaration = true; 559 Expanded.BraceWrapping.AfterStruct = true; 560 Expanded.BraceWrapping.AfterExternBlock = true; 561 Expanded.BraceWrapping.BeforeCatch = true; 562 Expanded.BraceWrapping.BeforeElse = true; 563 break; 564 case FormatStyle::BS_GNU: 565 Expanded.BraceWrapping = {true, true, true, true, true, true, true, true, 566 true, true, true, true, true, true, true}; 567 break; 568 case FormatStyle::BS_WebKit: 569 Expanded.BraceWrapping.AfterFunction = true; 570 break; 571 default: 572 break; 573 } 574 return Expanded; 575 } 576 577 FormatStyle getLLVMStyle() { 578 FormatStyle LLVMStyle; 579 LLVMStyle.Language = FormatStyle::LK_Cpp; 580 LLVMStyle.AccessModifierOffset = -2; 581 LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right; 582 LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align; 583 LLVMStyle.AlignOperands = true; 584 LLVMStyle.AlignTrailingComments = true; 585 LLVMStyle.AlignConsecutiveAssignments = false; 586 LLVMStyle.AlignConsecutiveDeclarations = false; 587 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; 588 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 589 LLVMStyle.AllowShortBlocksOnASingleLine = false; 590 LLVMStyle.AllowShortCaseLabelsOnASingleLine = false; 591 LLVMStyle.AllowShortIfStatementsOnASingleLine = false; 592 LLVMStyle.AllowShortLoopsOnASingleLine = false; 593 LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 594 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None; 595 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false; 596 LLVMStyle.AlwaysBreakTemplateDeclarations = false; 597 LLVMStyle.BinPackArguments = true; 598 LLVMStyle.BinPackParameters = true; 599 LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 600 LLVMStyle.BreakBeforeTernaryOperators = true; 601 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; 602 LLVMStyle.BraceWrapping = {false, false, false, false, false, 603 false, false, false, false, false, 604 false, false, true, true, true}; 605 LLVMStyle.BreakAfterJavaFieldAnnotations = false; 606 LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 607 LLVMStyle.BreakBeforeInheritanceComma = false; 608 LLVMStyle.BreakStringLiterals = true; 609 LLVMStyle.ColumnLimit = 80; 610 LLVMStyle.CommentPragmas = "^ IWYU pragma:"; 611 LLVMStyle.CompactNamespaces = false; 612 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 613 LLVMStyle.ConstructorInitializerIndentWidth = 4; 614 LLVMStyle.ContinuationIndentWidth = 4; 615 LLVMStyle.Cpp11BracedListStyle = true; 616 LLVMStyle.DerivePointerAlignment = false; 617 LLVMStyle.ExperimentalAutoDetectBinPacking = false; 618 LLVMStyle.FixNamespaceComments = true; 619 LLVMStyle.ForEachMacros.push_back("foreach"); 620 LLVMStyle.ForEachMacros.push_back("Q_FOREACH"); 621 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH"); 622 LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2}, 623 {"^(<|\"(gtest|gmock|isl|json)/)", 3}, 624 {".*", 1}}; 625 LLVMStyle.IncludeIsMainRegex = "(Test)?$"; 626 LLVMStyle.IncludeBlocks = FormatStyle::IBS_Preserve; 627 LLVMStyle.IndentCaseLabels = false; 628 LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None; 629 LLVMStyle.IndentWrappedFunctionNames = false; 630 LLVMStyle.IndentWidth = 2; 631 LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave; 632 LLVMStyle.JavaScriptWrapImports = true; 633 LLVMStyle.TabWidth = 8; 634 LLVMStyle.MaxEmptyLinesToKeep = 1; 635 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true; 636 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None; 637 LLVMStyle.ObjCBlockIndentWidth = 2; 638 LLVMStyle.ObjCSpaceAfterProperty = false; 639 LLVMStyle.ObjCSpaceBeforeProtocolList = true; 640 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right; 641 LLVMStyle.SpacesBeforeTrailingComments = 1; 642 LLVMStyle.Standard = FormatStyle::LS_Cpp11; 643 LLVMStyle.UseTab = FormatStyle::UT_Never; 644 LLVMStyle.RawStringFormats = {{"pb", FormatStyle::LK_TextProto, "google"}}; 645 LLVMStyle.ReflowComments = true; 646 LLVMStyle.SpacesInParentheses = false; 647 LLVMStyle.SpacesInSquareBrackets = false; 648 LLVMStyle.SpaceInEmptyParentheses = false; 649 LLVMStyle.SpacesInContainerLiterals = true; 650 LLVMStyle.SpacesInCStyleCastParentheses = false; 651 LLVMStyle.SpaceAfterCStyleCast = false; 652 LLVMStyle.SpaceAfterTemplateKeyword = true; 653 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements; 654 LLVMStyle.SpaceBeforeAssignmentOperators = true; 655 LLVMStyle.SpacesInAngles = false; 656 657 LLVMStyle.PenaltyBreakAssignment = prec::Assignment; 658 LLVMStyle.PenaltyBreakComment = 300; 659 LLVMStyle.PenaltyBreakFirstLessLess = 120; 660 LLVMStyle.PenaltyBreakString = 1000; 661 LLVMStyle.PenaltyExcessCharacter = 1000000; 662 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60; 663 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19; 664 665 LLVMStyle.DisableFormat = false; 666 LLVMStyle.SortIncludes = true; 667 LLVMStyle.SortUsingDeclarations = true; 668 669 return LLVMStyle; 670 } 671 672 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { 673 if (Language == FormatStyle::LK_TextProto) { 674 FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto); 675 GoogleStyle.Language = FormatStyle::LK_TextProto; 676 return GoogleStyle; 677 } 678 679 FormatStyle GoogleStyle = getLLVMStyle(); 680 GoogleStyle.Language = Language; 681 682 GoogleStyle.AccessModifierOffset = -1; 683 GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left; 684 GoogleStyle.AllowShortIfStatementsOnASingleLine = true; 685 GoogleStyle.AllowShortLoopsOnASingleLine = true; 686 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; 687 GoogleStyle.AlwaysBreakTemplateDeclarations = true; 688 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 689 GoogleStyle.DerivePointerAlignment = true; 690 GoogleStyle.IncludeCategories = { 691 {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}}; 692 GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$"; 693 GoogleStyle.IndentCaseLabels = true; 694 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 695 GoogleStyle.ObjCSpaceAfterProperty = false; 696 GoogleStyle.ObjCSpaceBeforeProtocolList = false; 697 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left; 698 GoogleStyle.SpacesBeforeTrailingComments = 2; 699 GoogleStyle.Standard = FormatStyle::LS_Auto; 700 701 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; 702 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1; 703 704 if (Language == FormatStyle::LK_Java) { 705 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 706 GoogleStyle.AlignOperands = false; 707 GoogleStyle.AlignTrailingComments = false; 708 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 709 GoogleStyle.AllowShortIfStatementsOnASingleLine = false; 710 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; 711 GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 712 GoogleStyle.ColumnLimit = 100; 713 GoogleStyle.SpaceAfterCStyleCast = true; 714 GoogleStyle.SpacesBeforeTrailingComments = 1; 715 } else if (Language == FormatStyle::LK_JavaScript) { 716 GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 717 GoogleStyle.AlignOperands = false; 718 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 719 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; 720 GoogleStyle.BreakBeforeTernaryOperators = false; 721 // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot 722 // of JSDoc tags, and @see, which is commonly followed by overlong URLs. 723 GoogleStyle.CommentPragmas = 724 "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)"; 725 GoogleStyle.MaxEmptyLinesToKeep = 3; 726 GoogleStyle.NamespaceIndentation = FormatStyle::NI_All; 727 GoogleStyle.SpacesInContainerLiterals = false; 728 GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single; 729 GoogleStyle.JavaScriptWrapImports = false; 730 } else if (Language == FormatStyle::LK_Proto) { 731 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 732 GoogleStyle.SpacesInContainerLiterals = false; 733 } else if (Language == FormatStyle::LK_ObjC) { 734 GoogleStyle.ColumnLimit = 100; 735 } 736 737 return GoogleStyle; 738 } 739 740 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) { 741 FormatStyle ChromiumStyle = getGoogleStyle(Language); 742 if (Language == FormatStyle::LK_Java) { 743 ChromiumStyle.AllowShortIfStatementsOnASingleLine = true; 744 ChromiumStyle.BreakAfterJavaFieldAnnotations = true; 745 ChromiumStyle.ContinuationIndentWidth = 8; 746 ChromiumStyle.IndentWidth = 4; 747 } else if (Language == FormatStyle::LK_JavaScript) { 748 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; 749 ChromiumStyle.AllowShortLoopsOnASingleLine = false; 750 } else { 751 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; 752 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 753 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; 754 ChromiumStyle.AllowShortLoopsOnASingleLine = false; 755 ChromiumStyle.BinPackParameters = false; 756 ChromiumStyle.DerivePointerAlignment = false; 757 if (Language == FormatStyle::LK_ObjC) 758 ChromiumStyle.ColumnLimit = 80; 759 } 760 return ChromiumStyle; 761 } 762 763 FormatStyle getMozillaStyle() { 764 FormatStyle MozillaStyle = getLLVMStyle(); 765 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; 766 MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 767 MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 768 MozillaStyle.AlwaysBreakAfterDefinitionReturnType = 769 FormatStyle::DRTBS_TopLevel; 770 MozillaStyle.AlwaysBreakTemplateDeclarations = true; 771 MozillaStyle.BinPackParameters = false; 772 MozillaStyle.BinPackArguments = false; 773 MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 774 MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 775 MozillaStyle.BreakBeforeInheritanceComma = true; 776 MozillaStyle.ConstructorInitializerIndentWidth = 2; 777 MozillaStyle.ContinuationIndentWidth = 2; 778 MozillaStyle.Cpp11BracedListStyle = false; 779 MozillaStyle.FixNamespaceComments = false; 780 MozillaStyle.IndentCaseLabels = true; 781 MozillaStyle.ObjCSpaceAfterProperty = true; 782 MozillaStyle.ObjCSpaceBeforeProtocolList = false; 783 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; 784 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left; 785 MozillaStyle.SpaceAfterTemplateKeyword = false; 786 return MozillaStyle; 787 } 788 789 FormatStyle getWebKitStyle() { 790 FormatStyle Style = getLLVMStyle(); 791 Style.AccessModifierOffset = -4; 792 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 793 Style.AlignOperands = false; 794 Style.AlignTrailingComments = false; 795 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 796 Style.BreakBeforeBraces = FormatStyle::BS_WebKit; 797 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 798 Style.Cpp11BracedListStyle = false; 799 Style.ColumnLimit = 0; 800 Style.FixNamespaceComments = false; 801 Style.IndentWidth = 4; 802 Style.NamespaceIndentation = FormatStyle::NI_Inner; 803 Style.ObjCBlockIndentWidth = 4; 804 Style.ObjCSpaceAfterProperty = true; 805 Style.PointerAlignment = FormatStyle::PAS_Left; 806 return Style; 807 } 808 809 FormatStyle getGNUStyle() { 810 FormatStyle Style = getLLVMStyle(); 811 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 812 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 813 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 814 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 815 Style.BreakBeforeTernaryOperators = true; 816 Style.Cpp11BracedListStyle = false; 817 Style.ColumnLimit = 79; 818 Style.FixNamespaceComments = false; 819 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 820 Style.Standard = FormatStyle::LS_Cpp03; 821 return Style; 822 } 823 824 FormatStyle getNoStyle() { 825 FormatStyle NoStyle = getLLVMStyle(); 826 NoStyle.DisableFormat = true; 827 NoStyle.SortIncludes = false; 828 NoStyle.SortUsingDeclarations = false; 829 return NoStyle; 830 } 831 832 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, 833 FormatStyle *Style) { 834 if (Name.equals_lower("llvm")) { 835 *Style = getLLVMStyle(); 836 } else if (Name.equals_lower("chromium")) { 837 *Style = getChromiumStyle(Language); 838 } else if (Name.equals_lower("mozilla")) { 839 *Style = getMozillaStyle(); 840 } else if (Name.equals_lower("google")) { 841 *Style = getGoogleStyle(Language); 842 } else if (Name.equals_lower("webkit")) { 843 *Style = getWebKitStyle(); 844 } else if (Name.equals_lower("gnu")) { 845 *Style = getGNUStyle(); 846 } else if (Name.equals_lower("none")) { 847 *Style = getNoStyle(); 848 } else { 849 return false; 850 } 851 852 Style->Language = Language; 853 return true; 854 } 855 856 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { 857 assert(Style); 858 FormatStyle::LanguageKind Language = Style->Language; 859 assert(Language != FormatStyle::LK_None); 860 if (Text.trim().empty()) 861 return make_error_code(ParseError::Error); 862 Style->StyleSet.Clear(); 863 std::vector<FormatStyle> Styles; 864 llvm::yaml::Input Input(Text); 865 // DocumentListTraits<vector<FormatStyle>> uses the context to get default 866 // values for the fields, keys for which are missing from the configuration. 867 // Mapping also uses the context to get the language to find the correct 868 // base style. 869 Input.setContext(Style); 870 Input >> Styles; 871 if (Input.error()) 872 return Input.error(); 873 874 for (unsigned i = 0; i < Styles.size(); ++i) { 875 // Ensures that only the first configuration can skip the Language option. 876 if (Styles[i].Language == FormatStyle::LK_None && i != 0) 877 return make_error_code(ParseError::Error); 878 // Ensure that each language is configured at most once. 879 for (unsigned j = 0; j < i; ++j) { 880 if (Styles[i].Language == Styles[j].Language) { 881 DEBUG(llvm::dbgs() 882 << "Duplicate languages in the config file on positions " << j 883 << " and " << i << "\n"); 884 return make_error_code(ParseError::Error); 885 } 886 } 887 } 888 // Look for a suitable configuration starting from the end, so we can 889 // find the configuration for the specific language first, and the default 890 // configuration (which can only be at slot 0) after it. 891 FormatStyle::FormatStyleSet StyleSet; 892 bool LanguageFound = false; 893 for (int i = Styles.size() - 1; i >= 0; --i) { 894 if (Styles[i].Language != FormatStyle::LK_None) 895 StyleSet.Add(Styles[i]); 896 if (Styles[i].Language == Language) 897 LanguageFound = true; 898 } 899 if (!LanguageFound) { 900 if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None) 901 return make_error_code(ParseError::Unsuitable); 902 FormatStyle DefaultStyle = Styles[0]; 903 DefaultStyle.Language = Language; 904 StyleSet.Add(std::move(DefaultStyle)); 905 } 906 *Style = *StyleSet.Get(Language); 907 return make_error_code(ParseError::Success); 908 } 909 910 std::string configurationAsText(const FormatStyle &Style) { 911 std::string Text; 912 llvm::raw_string_ostream Stream(Text); 913 llvm::yaml::Output Output(Stream); 914 // We use the same mapping method for input and output, so we need a non-const 915 // reference here. 916 FormatStyle NonConstStyle = expandPresets(Style); 917 Output << NonConstStyle; 918 return Stream.str(); 919 } 920 921 llvm::Optional<FormatStyle> 922 FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const { 923 if (!Styles) 924 return None; 925 auto It = Styles->find(Language); 926 if (It == Styles->end()) 927 return None; 928 FormatStyle Style = It->second; 929 Style.StyleSet = *this; 930 return Style; 931 } 932 933 void FormatStyle::FormatStyleSet::Add(FormatStyle Style) { 934 assert(Style.Language != LK_None && 935 "Cannot add a style for LK_None to a StyleSet"); 936 assert( 937 !Style.StyleSet.Styles && 938 "Cannot add a style associated with an existing StyleSet to a StyleSet"); 939 if (!Styles) 940 Styles = std::make_shared<MapType>(); 941 (*Styles)[Style.Language] = std::move(Style); 942 } 943 944 void FormatStyle::FormatStyleSet::Clear() { 945 Styles.reset(); 946 } 947 948 llvm::Optional<FormatStyle> 949 FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const { 950 return StyleSet.Get(Language); 951 } 952 953 namespace { 954 955 class JavaScriptRequoter : public TokenAnalyzer { 956 public: 957 JavaScriptRequoter(const Environment &Env, const FormatStyle &Style) 958 : TokenAnalyzer(Env, Style) {} 959 960 std::pair<tooling::Replacements, unsigned> 961 analyze(TokenAnnotator &Annotator, 962 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 963 FormatTokenLexer &Tokens) override { 964 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(), 965 AnnotatedLines.end()); 966 tooling::Replacements Result; 967 requoteJSStringLiteral(AnnotatedLines, Result); 968 return {Result, 0}; 969 } 970 971 private: 972 // Replaces double/single-quoted string literal as appropriate, re-escaping 973 // the contents in the process. 974 void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines, 975 tooling::Replacements &Result) { 976 for (AnnotatedLine *Line : Lines) { 977 requoteJSStringLiteral(Line->Children, Result); 978 if (!Line->Affected) 979 continue; 980 for (FormatToken *FormatTok = Line->First; FormatTok; 981 FormatTok = FormatTok->Next) { 982 StringRef Input = FormatTok->TokenText; 983 if (FormatTok->Finalized || !FormatTok->isStringLiteral() || 984 // NB: testing for not starting with a double quote to avoid 985 // breaking `template strings`. 986 (Style.JavaScriptQuotes == FormatStyle::JSQS_Single && 987 !Input.startswith("\"")) || 988 (Style.JavaScriptQuotes == FormatStyle::JSQS_Double && 989 !Input.startswith("\'"))) 990 continue; 991 992 // Change start and end quote. 993 bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single; 994 SourceLocation Start = FormatTok->Tok.getLocation(); 995 auto Replace = [&](SourceLocation Start, unsigned Length, 996 StringRef ReplacementText) { 997 auto Err = Result.add(tooling::Replacement( 998 Env.getSourceManager(), Start, Length, ReplacementText)); 999 // FIXME: handle error. For now, print error message and skip the 1000 // replacement for release version. 1001 if (Err) { 1002 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 1003 assert(false); 1004 } 1005 }; 1006 Replace(Start, 1, IsSingle ? "'" : "\""); 1007 Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1, 1008 IsSingle ? "'" : "\""); 1009 1010 // Escape internal quotes. 1011 bool Escaped = false; 1012 for (size_t i = 1; i < Input.size() - 1; i++) { 1013 switch (Input[i]) { 1014 case '\\': 1015 if (!Escaped && i + 1 < Input.size() && 1016 ((IsSingle && Input[i + 1] == '"') || 1017 (!IsSingle && Input[i + 1] == '\''))) { 1018 // Remove this \, it's escaping a " or ' that no longer needs 1019 // escaping 1020 Replace(Start.getLocWithOffset(i), 1, ""); 1021 continue; 1022 } 1023 Escaped = !Escaped; 1024 break; 1025 case '\"': 1026 case '\'': 1027 if (!Escaped && IsSingle == (Input[i] == '\'')) { 1028 // Escape the quote. 1029 Replace(Start.getLocWithOffset(i), 0, "\\"); 1030 } 1031 Escaped = false; 1032 break; 1033 default: 1034 Escaped = false; 1035 break; 1036 } 1037 } 1038 } 1039 } 1040 } 1041 }; 1042 1043 class Formatter : public TokenAnalyzer { 1044 public: 1045 Formatter(const Environment &Env, const FormatStyle &Style, 1046 FormattingAttemptStatus *Status) 1047 : TokenAnalyzer(Env, Style), Status(Status) {} 1048 1049 std::pair<tooling::Replacements, unsigned> 1050 analyze(TokenAnnotator &Annotator, 1051 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 1052 FormatTokenLexer &Tokens) override { 1053 tooling::Replacements Result; 1054 deriveLocalStyle(AnnotatedLines); 1055 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(), 1056 AnnotatedLines.end()); 1057 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1058 Annotator.calculateFormattingInformation(*AnnotatedLines[i]); 1059 } 1060 Annotator.setCommentLineLevels(AnnotatedLines); 1061 1062 WhitespaceManager Whitespaces( 1063 Env.getSourceManager(), Style, 1064 inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID()))); 1065 ContinuationIndenter Indenter(Style, Tokens.getKeywords(), 1066 Env.getSourceManager(), Whitespaces, Encoding, 1067 BinPackInconclusiveFunctions); 1068 unsigned Penalty = 1069 UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, 1070 Tokens.getKeywords(), Env.getSourceManager(), 1071 Status) 1072 .format(AnnotatedLines, /*DryRun=*/false, 1073 /*AdditionalIndent=*/0, 1074 /*FixBadIndentation=*/false, 1075 /*FirstStartColumn=*/Env.getFirstStartColumn(), 1076 /*NextStartColumn=*/Env.getNextStartColumn(), 1077 /*LastStartColumn=*/Env.getLastStartColumn()); 1078 for (const auto &R : Whitespaces.generateReplacements()) 1079 if (Result.add(R)) 1080 return std::make_pair(Result, 0); 1081 return std::make_pair(Result, Penalty); 1082 } 1083 1084 private: 1085 static bool inputUsesCRLF(StringRef Text) { 1086 return Text.count('\r') * 2 > Text.count('\n'); 1087 } 1088 1089 bool 1090 hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) { 1091 for (const AnnotatedLine *Line : Lines) { 1092 if (hasCpp03IncompatibleFormat(Line->Children)) 1093 return true; 1094 for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) { 1095 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) { 1096 if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener)) 1097 return true; 1098 if (Tok->is(TT_TemplateCloser) && 1099 Tok->Previous->is(TT_TemplateCloser)) 1100 return true; 1101 } 1102 } 1103 } 1104 return false; 1105 } 1106 1107 int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) { 1108 int AlignmentDiff = 0; 1109 for (const AnnotatedLine *Line : Lines) { 1110 AlignmentDiff += countVariableAlignments(Line->Children); 1111 for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) { 1112 if (!Tok->is(TT_PointerOrReference)) 1113 continue; 1114 bool SpaceBefore = 1115 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd(); 1116 bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() != 1117 Tok->Next->WhitespaceRange.getEnd(); 1118 if (SpaceBefore && !SpaceAfter) 1119 ++AlignmentDiff; 1120 if (!SpaceBefore && SpaceAfter) 1121 --AlignmentDiff; 1122 } 1123 } 1124 return AlignmentDiff; 1125 } 1126 1127 void 1128 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 1129 bool HasBinPackedFunction = false; 1130 bool HasOnePerLineFunction = false; 1131 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1132 if (!AnnotatedLines[i]->First->Next) 1133 continue; 1134 FormatToken *Tok = AnnotatedLines[i]->First->Next; 1135 while (Tok->Next) { 1136 if (Tok->PackingKind == PPK_BinPacked) 1137 HasBinPackedFunction = true; 1138 if (Tok->PackingKind == PPK_OnePerLine) 1139 HasOnePerLineFunction = true; 1140 1141 Tok = Tok->Next; 1142 } 1143 } 1144 if (Style.DerivePointerAlignment) 1145 Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0 1146 ? FormatStyle::PAS_Left 1147 : FormatStyle::PAS_Right; 1148 if (Style.Standard == FormatStyle::LS_Auto) 1149 Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines) 1150 ? FormatStyle::LS_Cpp11 1151 : FormatStyle::LS_Cpp03; 1152 BinPackInconclusiveFunctions = 1153 HasBinPackedFunction || !HasOnePerLineFunction; 1154 } 1155 1156 bool BinPackInconclusiveFunctions; 1157 FormattingAttemptStatus *Status; 1158 }; 1159 1160 // This class clean up the erroneous/redundant code around the given ranges in 1161 // file. 1162 class Cleaner : public TokenAnalyzer { 1163 public: 1164 Cleaner(const Environment &Env, const FormatStyle &Style) 1165 : TokenAnalyzer(Env, Style), 1166 DeletedTokens(FormatTokenLess(Env.getSourceManager())) {} 1167 1168 // FIXME: eliminate unused parameters. 1169 std::pair<tooling::Replacements, unsigned> 1170 analyze(TokenAnnotator &Annotator, 1171 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 1172 FormatTokenLexer &Tokens) override { 1173 // FIXME: in the current implementation the granularity of affected range 1174 // is an annotated line. However, this is not sufficient. Furthermore, 1175 // redundant code introduced by replacements does not necessarily 1176 // intercept with ranges of replacements that result in the redundancy. 1177 // To determine if some redundant code is actually introduced by 1178 // replacements(e.g. deletions), we need to come up with a more 1179 // sophisticated way of computing affected ranges. 1180 AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(), 1181 AnnotatedLines.end()); 1182 1183 checkEmptyNamespace(AnnotatedLines); 1184 1185 for (auto &Line : AnnotatedLines) { 1186 if (Line->Affected) { 1187 cleanupRight(Line->First, tok::comma, tok::comma); 1188 cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma); 1189 cleanupRight(Line->First, tok::l_paren, tok::comma); 1190 cleanupLeft(Line->First, tok::comma, tok::r_paren); 1191 cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace); 1192 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace); 1193 cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal); 1194 } 1195 } 1196 1197 return {generateFixes(), 0}; 1198 } 1199 1200 private: 1201 bool containsOnlyComments(const AnnotatedLine &Line) { 1202 for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) { 1203 if (Tok->isNot(tok::comment)) 1204 return false; 1205 } 1206 return true; 1207 } 1208 1209 // Iterate through all lines and remove any empty (nested) namespaces. 1210 void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 1211 std::set<unsigned> DeletedLines; 1212 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1213 auto &Line = *AnnotatedLines[i]; 1214 if (Line.startsWith(tok::kw_namespace) || 1215 Line.startsWith(tok::kw_inline, tok::kw_namespace)) { 1216 checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines); 1217 } 1218 } 1219 1220 for (auto Line : DeletedLines) { 1221 FormatToken *Tok = AnnotatedLines[Line]->First; 1222 while (Tok) { 1223 deleteToken(Tok); 1224 Tok = Tok->Next; 1225 } 1226 } 1227 } 1228 1229 // The function checks if the namespace, which starts from \p CurrentLine, and 1230 // its nested namespaces are empty and delete them if they are empty. It also 1231 // sets \p NewLine to the last line checked. 1232 // Returns true if the current namespace is empty. 1233 bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 1234 unsigned CurrentLine, unsigned &NewLine, 1235 std::set<unsigned> &DeletedLines) { 1236 unsigned InitLine = CurrentLine, End = AnnotatedLines.size(); 1237 if (Style.BraceWrapping.AfterNamespace) { 1238 // If the left brace is in a new line, we should consume it first so that 1239 // it does not make the namespace non-empty. 1240 // FIXME: error handling if there is no left brace. 1241 if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) { 1242 NewLine = CurrentLine; 1243 return false; 1244 } 1245 } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) { 1246 return false; 1247 } 1248 while (++CurrentLine < End) { 1249 if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace)) 1250 break; 1251 1252 if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) || 1253 AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline, 1254 tok::kw_namespace)) { 1255 if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine, 1256 DeletedLines)) 1257 return false; 1258 CurrentLine = NewLine; 1259 continue; 1260 } 1261 1262 if (containsOnlyComments(*AnnotatedLines[CurrentLine])) 1263 continue; 1264 1265 // If there is anything other than comments or nested namespaces in the 1266 // current namespace, the namespace cannot be empty. 1267 NewLine = CurrentLine; 1268 return false; 1269 } 1270 1271 NewLine = CurrentLine; 1272 if (CurrentLine >= End) 1273 return false; 1274 1275 // Check if the empty namespace is actually affected by changed ranges. 1276 if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange( 1277 AnnotatedLines[InitLine]->First->Tok.getLocation(), 1278 AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) 1279 return false; 1280 1281 for (unsigned i = InitLine; i <= CurrentLine; ++i) { 1282 DeletedLines.insert(i); 1283 } 1284 1285 return true; 1286 } 1287 1288 // Checks pairs {start, start->next},..., {end->previous, end} and deletes one 1289 // of the token in the pair if the left token has \p LK token kind and the 1290 // right token has \p RK token kind. If \p DeleteLeft is true, the left token 1291 // is deleted on match; otherwise, the right token is deleted. 1292 template <typename LeftKind, typename RightKind> 1293 void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK, 1294 bool DeleteLeft) { 1295 auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * { 1296 for (auto *Res = Tok.Next; Res; Res = Res->Next) 1297 if (!Res->is(tok::comment) && 1298 DeletedTokens.find(Res) == DeletedTokens.end()) 1299 return Res; 1300 return nullptr; 1301 }; 1302 for (auto *Left = Start; Left;) { 1303 auto *Right = NextNotDeleted(*Left); 1304 if (!Right) 1305 break; 1306 if (Left->is(LK) && Right->is(RK)) { 1307 deleteToken(DeleteLeft ? Left : Right); 1308 for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next) 1309 deleteToken(Tok); 1310 // If the right token is deleted, we should keep the left token 1311 // unchanged and pair it with the new right token. 1312 if (!DeleteLeft) 1313 continue; 1314 } 1315 Left = Right; 1316 } 1317 } 1318 1319 template <typename LeftKind, typename RightKind> 1320 void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) { 1321 cleanupPair(Start, LK, RK, /*DeleteLeft=*/true); 1322 } 1323 1324 template <typename LeftKind, typename RightKind> 1325 void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) { 1326 cleanupPair(Start, LK, RK, /*DeleteLeft=*/false); 1327 } 1328 1329 // Delete the given token. 1330 inline void deleteToken(FormatToken *Tok) { 1331 if (Tok) 1332 DeletedTokens.insert(Tok); 1333 } 1334 1335 tooling::Replacements generateFixes() { 1336 tooling::Replacements Fixes; 1337 std::vector<FormatToken *> Tokens; 1338 std::copy(DeletedTokens.begin(), DeletedTokens.end(), 1339 std::back_inserter(Tokens)); 1340 1341 // Merge multiple continuous token deletions into one big deletion so that 1342 // the number of replacements can be reduced. This makes computing affected 1343 // ranges more efficient when we run reformat on the changed code. 1344 unsigned Idx = 0; 1345 while (Idx < Tokens.size()) { 1346 unsigned St = Idx, End = Idx; 1347 while ((End + 1) < Tokens.size() && 1348 Tokens[End]->Next == Tokens[End + 1]) { 1349 End++; 1350 } 1351 auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(), 1352 Tokens[End]->Tok.getEndLoc()); 1353 auto Err = 1354 Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, "")); 1355 // FIXME: better error handling. for now just print error message and skip 1356 // for the release version. 1357 if (Err) { 1358 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 1359 assert(false && "Fixes must not conflict!"); 1360 } 1361 Idx = End + 1; 1362 } 1363 1364 return Fixes; 1365 } 1366 1367 // Class for less-than inequality comparason for the set `RedundantTokens`. 1368 // We store tokens in the order they appear in the translation unit so that 1369 // we do not need to sort them in `generateFixes()`. 1370 struct FormatTokenLess { 1371 FormatTokenLess(const SourceManager &SM) : SM(SM) {} 1372 1373 bool operator()(const FormatToken *LHS, const FormatToken *RHS) const { 1374 return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(), 1375 RHS->Tok.getLocation()); 1376 } 1377 const SourceManager &SM; 1378 }; 1379 1380 // Tokens to be deleted. 1381 std::set<FormatToken *, FormatTokenLess> DeletedTokens; 1382 }; 1383 1384 struct IncludeDirective { 1385 StringRef Filename; 1386 StringRef Text; 1387 unsigned Offset; 1388 int Category; 1389 }; 1390 1391 } // end anonymous namespace 1392 1393 // Determines whether 'Ranges' intersects with ('Start', 'End'). 1394 static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start, 1395 unsigned End) { 1396 for (auto Range : Ranges) { 1397 if (Range.getOffset() < End && 1398 Range.getOffset() + Range.getLength() > Start) 1399 return true; 1400 } 1401 return false; 1402 } 1403 1404 // Returns a pair (Index, OffsetToEOL) describing the position of the cursor 1405 // before sorting/deduplicating. Index is the index of the include under the 1406 // cursor in the original set of includes. If this include has duplicates, it is 1407 // the index of the first of the duplicates as the others are going to be 1408 // removed. OffsetToEOL describes the cursor's position relative to the end of 1409 // its current line. 1410 // If `Cursor` is not on any #include, `Index` will be UINT_MAX. 1411 static std::pair<unsigned, unsigned> 1412 FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes, 1413 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) { 1414 unsigned CursorIndex = UINT_MAX; 1415 unsigned OffsetToEOL = 0; 1416 for (int i = 0, e = Includes.size(); i != e; ++i) { 1417 unsigned Start = Includes[Indices[i]].Offset; 1418 unsigned End = Start + Includes[Indices[i]].Text.size(); 1419 if (!(Cursor >= Start && Cursor < End)) 1420 continue; 1421 CursorIndex = Indices[i]; 1422 OffsetToEOL = End - Cursor; 1423 // Put the cursor on the only remaining #include among the duplicate 1424 // #includes. 1425 while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text) 1426 CursorIndex = i; 1427 break; 1428 } 1429 return std::make_pair(CursorIndex, OffsetToEOL); 1430 } 1431 1432 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically 1433 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict 1434 // source order. 1435 // #include directives with the same text will be deduplicated, and only the 1436 // first #include in the duplicate #includes remains. If the `Cursor` is 1437 // provided and put on a deleted #include, it will be moved to the remaining 1438 // #include in the duplicate #includes. 1439 static void sortCppIncludes(const FormatStyle &Style, 1440 const SmallVectorImpl<IncludeDirective> &Includes, 1441 ArrayRef<tooling::Range> Ranges, StringRef FileName, 1442 tooling::Replacements &Replaces, unsigned *Cursor) { 1443 unsigned IncludesBeginOffset = Includes.front().Offset; 1444 unsigned IncludesEndOffset = 1445 Includes.back().Offset + Includes.back().Text.size(); 1446 unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset; 1447 if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset)) 1448 return; 1449 SmallVector<unsigned, 16> Indices; 1450 for (unsigned i = 0, e = Includes.size(); i != e; ++i) 1451 Indices.push_back(i); 1452 std::stable_sort( 1453 Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) { 1454 return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) < 1455 std::tie(Includes[RHSI].Category, Includes[RHSI].Filename); 1456 }); 1457 // The index of the include on which the cursor will be put after 1458 // sorting/deduplicating. 1459 unsigned CursorIndex; 1460 // The offset from cursor to the end of line. 1461 unsigned CursorToEOLOffset; 1462 if (Cursor) 1463 std::tie(CursorIndex, CursorToEOLOffset) = 1464 FindCursorIndex(Includes, Indices, *Cursor); 1465 1466 // Deduplicate #includes. 1467 Indices.erase(std::unique(Indices.begin(), Indices.end(), 1468 [&](unsigned LHSI, unsigned RHSI) { 1469 return Includes[LHSI].Text == Includes[RHSI].Text; 1470 }), 1471 Indices.end()); 1472 1473 int CurrentCategory = Includes.front().Category; 1474 1475 // If the #includes are out of order, we generate a single replacement fixing 1476 // the entire block. Otherwise, no replacement is generated. 1477 if (Indices.size() == Includes.size() && 1478 std::is_sorted(Indices.begin(), Indices.end()) && 1479 Style.IncludeBlocks == FormatStyle::IBS_Preserve) 1480 return; 1481 1482 std::string result; 1483 for (unsigned Index : Indices) { 1484 if (!result.empty()) { 1485 result += "\n"; 1486 if (Style.IncludeBlocks == FormatStyle::IBS_Regroup && 1487 CurrentCategory != Includes[Index].Category) 1488 result += "\n"; 1489 } 1490 result += Includes[Index].Text; 1491 if (Cursor && CursorIndex == Index) 1492 *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset; 1493 CurrentCategory = Includes[Index].Category; 1494 } 1495 1496 auto Err = Replaces.add(tooling::Replacement( 1497 FileName, Includes.front().Offset, IncludesBlockSize, result)); 1498 // FIXME: better error handling. For now, just skip the replacement for the 1499 // release version. 1500 if (Err) { 1501 llvm::errs() << llvm::toString(std::move(Err)) << "\n"; 1502 assert(false); 1503 } 1504 } 1505 1506 namespace { 1507 1508 // This class manages priorities of #include categories and calculates 1509 // priorities for headers. 1510 class IncludeCategoryManager { 1511 public: 1512 IncludeCategoryManager(const FormatStyle &Style, StringRef FileName) 1513 : Style(Style), FileName(FileName) { 1514 FileStem = llvm::sys::path::stem(FileName); 1515 for (const auto &Category : Style.IncludeCategories) 1516 CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase); 1517 IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") || 1518 FileName.endswith(".cpp") || FileName.endswith(".c++") || 1519 FileName.endswith(".cxx") || FileName.endswith(".m") || 1520 FileName.endswith(".mm"); 1521 } 1522 1523 // Returns the priority of the category which \p IncludeName belongs to. 1524 // If \p CheckMainHeader is true and \p IncludeName is a main header, returns 1525 // 0. Otherwise, returns the priority of the matching category or INT_MAX. 1526 int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) { 1527 int Ret = INT_MAX; 1528 for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) 1529 if (CategoryRegexs[i].match(IncludeName)) { 1530 Ret = Style.IncludeCategories[i].Priority; 1531 break; 1532 } 1533 if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName)) 1534 Ret = 0; 1535 return Ret; 1536 } 1537 1538 private: 1539 bool isMainHeader(StringRef IncludeName) const { 1540 if (!IncludeName.startswith("\"")) 1541 return false; 1542 StringRef HeaderStem = 1543 llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1)); 1544 if (FileStem.startswith(HeaderStem) || 1545 FileStem.startswith_lower(HeaderStem)) { 1546 llvm::Regex MainIncludeRegex( 1547 (HeaderStem + Style.IncludeIsMainRegex).str(), 1548 llvm::Regex::IgnoreCase); 1549 if (MainIncludeRegex.match(FileStem)) 1550 return true; 1551 } 1552 return false; 1553 } 1554 1555 const FormatStyle &Style; 1556 bool IsMainFile; 1557 StringRef FileName; 1558 StringRef FileStem; 1559 SmallVector<llvm::Regex, 4> CategoryRegexs; 1560 }; 1561 1562 const char IncludeRegexPattern[] = 1563 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))"; 1564 1565 } // anonymous namespace 1566 1567 tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code, 1568 ArrayRef<tooling::Range> Ranges, 1569 StringRef FileName, 1570 tooling::Replacements &Replaces, 1571 unsigned *Cursor) { 1572 unsigned Prev = 0; 1573 unsigned SearchFrom = 0; 1574 llvm::Regex IncludeRegex(IncludeRegexPattern); 1575 SmallVector<StringRef, 4> Matches; 1576 SmallVector<IncludeDirective, 16> IncludesInBlock; 1577 1578 // In compiled files, consider the first #include to be the main #include of 1579 // the file if it is not a system #include. This ensures that the header 1580 // doesn't have hidden dependencies 1581 // (http://llvm.org/docs/CodingStandards.html#include-style). 1582 // 1583 // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix 1584 // cases where the first #include is unlikely to be the main header. 1585 IncludeCategoryManager Categories(Style, FileName); 1586 bool FirstIncludeBlock = true; 1587 bool MainIncludeFound = false; 1588 bool FormattingOff = false; 1589 1590 for (;;) { 1591 auto Pos = Code.find('\n', SearchFrom); 1592 StringRef Line = 1593 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev); 1594 1595 StringRef Trimmed = Line.trim(); 1596 if (Trimmed == "// clang-format off") 1597 FormattingOff = true; 1598 else if (Trimmed == "// clang-format on") 1599 FormattingOff = false; 1600 1601 const bool EmptyLineSkipped = 1602 Trimmed.empty() && (Style.IncludeBlocks == FormatStyle::IBS_Merge || 1603 Style.IncludeBlocks == FormatStyle::IBS_Regroup); 1604 1605 if (!FormattingOff && !Line.endswith("\\")) { 1606 if (IncludeRegex.match(Line, &Matches)) { 1607 StringRef IncludeName = Matches[2]; 1608 int Category = Categories.getIncludePriority( 1609 IncludeName, 1610 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock); 1611 if (Category == 0) 1612 MainIncludeFound = true; 1613 IncludesInBlock.push_back({IncludeName, Line, Prev, Category}); 1614 } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) { 1615 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, 1616 Cursor); 1617 IncludesInBlock.clear(); 1618 FirstIncludeBlock = false; 1619 } 1620 Prev = Pos + 1; 1621 } 1622 if (Pos == StringRef::npos || Pos + 1 == Code.size()) 1623 break; 1624 SearchFrom = Pos + 1; 1625 } 1626 if (!IncludesInBlock.empty()) 1627 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor); 1628 return Replaces; 1629 } 1630 1631 bool isMpegTS(StringRef Code) { 1632 // MPEG transport streams use the ".ts" file extension. clang-format should 1633 // not attempt to format those. MPEG TS' frame format starts with 0x47 every 1634 // 189 bytes - detect that and return. 1635 return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47; 1636 } 1637 1638 bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); } 1639 1640 tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, 1641 ArrayRef<tooling::Range> Ranges, 1642 StringRef FileName, unsigned *Cursor) { 1643 tooling::Replacements Replaces; 1644 if (!Style.SortIncludes) 1645 return Replaces; 1646 if (isLikelyXml(Code)) 1647 return Replaces; 1648 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript && 1649 isMpegTS(Code)) 1650 return Replaces; 1651 if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript) 1652 return sortJavaScriptImports(Style, Code, Ranges, FileName); 1653 sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor); 1654 return Replaces; 1655 } 1656 1657 template <typename T> 1658 static llvm::Expected<tooling::Replacements> 1659 processReplacements(T ProcessFunc, StringRef Code, 1660 const tooling::Replacements &Replaces, 1661 const FormatStyle &Style) { 1662 if (Replaces.empty()) 1663 return tooling::Replacements(); 1664 1665 auto NewCode = applyAllReplacements(Code, Replaces); 1666 if (!NewCode) 1667 return NewCode.takeError(); 1668 std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges(); 1669 StringRef FileName = Replaces.begin()->getFilePath(); 1670 1671 tooling::Replacements FormatReplaces = 1672 ProcessFunc(Style, *NewCode, ChangedRanges, FileName); 1673 1674 return Replaces.merge(FormatReplaces); 1675 } 1676 1677 llvm::Expected<tooling::Replacements> 1678 formatReplacements(StringRef Code, const tooling::Replacements &Replaces, 1679 const FormatStyle &Style) { 1680 // We need to use lambda function here since there are two versions of 1681 // `sortIncludes`. 1682 auto SortIncludes = [](const FormatStyle &Style, StringRef Code, 1683 std::vector<tooling::Range> Ranges, 1684 StringRef FileName) -> tooling::Replacements { 1685 return sortIncludes(Style, Code, Ranges, FileName); 1686 }; 1687 auto SortedReplaces = 1688 processReplacements(SortIncludes, Code, Replaces, Style); 1689 if (!SortedReplaces) 1690 return SortedReplaces.takeError(); 1691 1692 // We need to use lambda function here since there are two versions of 1693 // `reformat`. 1694 auto Reformat = [](const FormatStyle &Style, StringRef Code, 1695 std::vector<tooling::Range> Ranges, 1696 StringRef FileName) -> tooling::Replacements { 1697 return reformat(Style, Code, Ranges, FileName); 1698 }; 1699 return processReplacements(Reformat, Code, *SortedReplaces, Style); 1700 } 1701 1702 namespace { 1703 1704 inline bool isHeaderInsertion(const tooling::Replacement &Replace) { 1705 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 && 1706 llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText()); 1707 } 1708 1709 inline bool isHeaderDeletion(const tooling::Replacement &Replace) { 1710 return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1; 1711 } 1712 1713 // Returns the offset after skipping a sequence of tokens, matched by \p 1714 // GetOffsetAfterSequence, from the start of the code. 1715 // \p GetOffsetAfterSequence should be a function that matches a sequence of 1716 // tokens and returns an offset after the sequence. 1717 unsigned getOffsetAfterTokenSequence( 1718 StringRef FileName, StringRef Code, const FormatStyle &Style, 1719 llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)> 1720 GetOffsetAfterSequence) { 1721 std::unique_ptr<Environment> Env = 1722 Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{}); 1723 const SourceManager &SourceMgr = Env->getSourceManager(); 1724 Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr, 1725 getFormattingLangOpts(Style)); 1726 Token Tok; 1727 // Get the first token. 1728 Lex.LexFromRawLexer(Tok); 1729 return GetOffsetAfterSequence(SourceMgr, Lex, Tok); 1730 } 1731 1732 // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is, 1733 // \p Tok will be the token after this directive; otherwise, it can be any token 1734 // after the given \p Tok (including \p Tok). 1735 bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) { 1736 bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) && 1737 Tok.is(tok::raw_identifier) && 1738 Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) && 1739 Tok.is(tok::raw_identifier); 1740 if (Matched) 1741 Lex.LexFromRawLexer(Tok); 1742 return Matched; 1743 } 1744 1745 void skipComments(Lexer &Lex, Token &Tok) { 1746 while (Tok.is(tok::comment)) 1747 if (Lex.LexFromRawLexer(Tok)) 1748 return; 1749 } 1750 1751 // Returns the offset after header guard directives and any comments 1752 // before/after header guards. If no header guard presents in the code, this 1753 // will returns the offset after skipping all comments from the start of the 1754 // code. 1755 unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName, 1756 StringRef Code, 1757 const FormatStyle &Style) { 1758 return getOffsetAfterTokenSequence( 1759 FileName, Code, Style, 1760 [](const SourceManager &SM, Lexer &Lex, Token Tok) { 1761 skipComments(Lex, Tok); 1762 unsigned InitialOffset = SM.getFileOffset(Tok.getLocation()); 1763 if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) { 1764 skipComments(Lex, Tok); 1765 if (checkAndConsumeDirectiveWithName(Lex, "define", Tok)) 1766 return SM.getFileOffset(Tok.getLocation()); 1767 } 1768 return InitialOffset; 1769 }); 1770 } 1771 1772 // Check if a sequence of tokens is like 1773 // "#include ("header.h" | <header.h>)". 1774 // If it is, \p Tok will be the token after this directive; otherwise, it can be 1775 // any token after the given \p Tok (including \p Tok). 1776 bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) { 1777 auto Matched = [&]() { 1778 Lex.LexFromRawLexer(Tok); 1779 return true; 1780 }; 1781 if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) && 1782 Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") { 1783 if (Lex.LexFromRawLexer(Tok)) 1784 return false; 1785 if (Tok.is(tok::string_literal)) 1786 return Matched(); 1787 if (Tok.is(tok::less)) { 1788 while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) { 1789 } 1790 if (Tok.is(tok::greater)) 1791 return Matched(); 1792 } 1793 } 1794 return false; 1795 } 1796 1797 // Returns the offset of the last #include directive after which a new 1798 // #include can be inserted. This ignores #include's after the #include block(s) 1799 // in the beginning of a file to avoid inserting headers into code sections 1800 // where new #include's should not be added by default. 1801 // These code sections include: 1802 // - raw string literals (containing #include). 1803 // - #if blocks. 1804 // - Special #include's among declarations (e.g. functions). 1805 // 1806 // If no #include after which a new #include can be inserted, this returns the 1807 // offset after skipping all comments from the start of the code. 1808 // Inserting after an #include is not allowed if it comes after code that is not 1809 // #include (e.g. pre-processing directive that is not #include, declarations). 1810 unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code, 1811 const FormatStyle &Style) { 1812 return getOffsetAfterTokenSequence( 1813 FileName, Code, Style, 1814 [](const SourceManager &SM, Lexer &Lex, Token Tok) { 1815 skipComments(Lex, Tok); 1816 unsigned MaxOffset = SM.getFileOffset(Tok.getLocation()); 1817 while (checkAndConsumeInclusiveDirective(Lex, Tok)) 1818 MaxOffset = SM.getFileOffset(Tok.getLocation()); 1819 return MaxOffset; 1820 }); 1821 } 1822 1823 bool isDeletedHeader(llvm::StringRef HeaderName, 1824 const std::set<llvm::StringRef> &HeadersToDelete) { 1825 return HeadersToDelete.count(HeaderName) || 1826 HeadersToDelete.count(HeaderName.trim("\"<>")); 1827 } 1828 1829 // FIXME: insert empty lines between newly created blocks. 1830 tooling::Replacements 1831 fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces, 1832 const FormatStyle &Style) { 1833 if (!Style.isCpp()) 1834 return Replaces; 1835 1836 tooling::Replacements HeaderInsertions; 1837 std::set<llvm::StringRef> HeadersToDelete; 1838 tooling::Replacements Result; 1839 for (const auto &R : Replaces) { 1840 if (isHeaderInsertion(R)) { 1841 // Replacements from \p Replaces must be conflict-free already, so we can 1842 // simply consume the error. 1843 llvm::consumeError(HeaderInsertions.add(R)); 1844 } else if (isHeaderDeletion(R)) { 1845 HeadersToDelete.insert(R.getReplacementText()); 1846 } else if (R.getOffset() == UINT_MAX) { 1847 llvm::errs() << "Insertions other than header #include insertion are " 1848 "not supported! " 1849 << R.getReplacementText() << "\n"; 1850 } else { 1851 llvm::consumeError(Result.add(R)); 1852 } 1853 } 1854 if (HeaderInsertions.empty() && HeadersToDelete.empty()) 1855 return Replaces; 1856 1857 llvm::Regex IncludeRegex(IncludeRegexPattern); 1858 llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)"); 1859 SmallVector<StringRef, 4> Matches; 1860 1861 StringRef FileName = Replaces.begin()->getFilePath(); 1862 IncludeCategoryManager Categories(Style, FileName); 1863 1864 // Record the offset of the end of the last include in each category. 1865 std::map<int, int> CategoryEndOffsets; 1866 // All possible priorities. 1867 // Add 0 for main header and INT_MAX for headers that are not in any category. 1868 std::set<int> Priorities = {0, INT_MAX}; 1869 for (const auto &Category : Style.IncludeCategories) 1870 Priorities.insert(Category.Priority); 1871 int FirstIncludeOffset = -1; 1872 // All new headers should be inserted after this offset. 1873 unsigned MinInsertOffset = 1874 getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style); 1875 StringRef TrimmedCode = Code.drop_front(MinInsertOffset); 1876 // Max insertion offset in the original code. 1877 unsigned MaxInsertOffset = 1878 MinInsertOffset + 1879 getMaxHeaderInsertionOffset(FileName, TrimmedCode, Style); 1880 SmallVector<StringRef, 32> Lines; 1881 TrimmedCode.split(Lines, '\n'); 1882 unsigned Offset = MinInsertOffset; 1883 unsigned NextLineOffset; 1884 std::set<StringRef> ExistingIncludes; 1885 for (auto Line : Lines) { 1886 NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1); 1887 if (IncludeRegex.match(Line, &Matches)) { 1888 // The header name with quotes or angle brackets. 1889 StringRef IncludeName = Matches[2]; 1890 ExistingIncludes.insert(IncludeName); 1891 // Only record the offset of current #include if we can insert after it. 1892 if (Offset <= MaxInsertOffset) { 1893 int Category = Categories.getIncludePriority( 1894 IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0); 1895 CategoryEndOffsets[Category] = NextLineOffset; 1896 if (FirstIncludeOffset < 0) 1897 FirstIncludeOffset = Offset; 1898 } 1899 if (isDeletedHeader(IncludeName, HeadersToDelete)) { 1900 // If this is the last line without trailing newline, we need to make 1901 // sure we don't delete across the file boundary. 1902 unsigned Length = std::min(Line.size() + 1, Code.size() - Offset); 1903 llvm::Error Err = 1904 Result.add(tooling::Replacement(FileName, Offset, Length, "")); 1905 if (Err) { 1906 // Ignore the deletion on conflict. 1907 llvm::errs() << "Failed to add header deletion replacement for " 1908 << IncludeName << ": " << llvm::toString(std::move(Err)) 1909 << "\n"; 1910 } 1911 } 1912 } 1913 Offset = NextLineOffset; 1914 } 1915 1916 // Populate CategoryEndOfssets: 1917 // - Ensure that CategoryEndOffset[Highest] is always populated. 1918 // - If CategoryEndOffset[Priority] isn't set, use the next higher value that 1919 // is set, up to CategoryEndOffset[Highest]. 1920 auto Highest = Priorities.begin(); 1921 if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) { 1922 if (FirstIncludeOffset >= 0) 1923 CategoryEndOffsets[*Highest] = FirstIncludeOffset; 1924 else 1925 CategoryEndOffsets[*Highest] = MinInsertOffset; 1926 } 1927 // By this point, CategoryEndOffset[Highest] is always set appropriately: 1928 // - to an appropriate location before/after existing #includes, or 1929 // - to right after the header guard, or 1930 // - to the beginning of the file. 1931 for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I) 1932 if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end()) 1933 CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)]; 1934 1935 bool NeedNewLineAtEnd = !Code.empty() && Code.back() != '\n'; 1936 for (const auto &R : HeaderInsertions) { 1937 auto IncludeDirective = R.getReplacementText(); 1938 bool Matched = IncludeRegex.match(IncludeDirective, &Matches); 1939 assert(Matched && "Header insertion replacement must have replacement text " 1940 "'#include ...'"); 1941 (void)Matched; 1942 auto IncludeName = Matches[2]; 1943 if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) { 1944 DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName 1945 << "\n"); 1946 continue; 1947 } 1948 int Category = 1949 Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true); 1950 Offset = CategoryEndOffsets[Category]; 1951 std::string NewInclude = !IncludeDirective.endswith("\n") 1952 ? (IncludeDirective + "\n").str() 1953 : IncludeDirective.str(); 1954 // When inserting headers at end of the code, also append '\n' to the code 1955 // if it does not end with '\n'. 1956 if (NeedNewLineAtEnd && Offset == Code.size()) { 1957 NewInclude = "\n" + NewInclude; 1958 NeedNewLineAtEnd = false; 1959 } 1960 auto NewReplace = tooling::Replacement(FileName, Offset, 0, NewInclude); 1961 auto Err = Result.add(NewReplace); 1962 if (Err) { 1963 llvm::consumeError(std::move(Err)); 1964 unsigned NewOffset = Result.getShiftedCodePosition(Offset); 1965 NewReplace = tooling::Replacement(FileName, NewOffset, 0, NewInclude); 1966 Result = Result.merge(tooling::Replacements(NewReplace)); 1967 } 1968 } 1969 return Result; 1970 } 1971 1972 } // anonymous namespace 1973 1974 llvm::Expected<tooling::Replacements> 1975 cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, 1976 const FormatStyle &Style) { 1977 // We need to use lambda function here since there are two versions of 1978 // `cleanup`. 1979 auto Cleanup = [](const FormatStyle &Style, StringRef Code, 1980 std::vector<tooling::Range> Ranges, 1981 StringRef FileName) -> tooling::Replacements { 1982 return cleanup(Style, Code, Ranges, FileName); 1983 }; 1984 // Make header insertion replacements insert new headers into correct blocks. 1985 tooling::Replacements NewReplaces = 1986 fixCppIncludeInsertions(Code, Replaces, Style); 1987 return processReplacements(Cleanup, Code, NewReplaces, Style); 1988 } 1989 1990 namespace internal { 1991 std::pair<tooling::Replacements, unsigned> 1992 reformat(const FormatStyle &Style, StringRef Code, 1993 ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn, 1994 unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, 1995 FormattingAttemptStatus *Status) { 1996 FormatStyle Expanded = expandPresets(Style); 1997 if (Expanded.DisableFormat) 1998 return {tooling::Replacements(), 0}; 1999 if (isLikelyXml(Code)) 2000 return {tooling::Replacements(), 0}; 2001 if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)) 2002 return {tooling::Replacements(), 0}; 2003 2004 typedef std::function<std::pair<tooling::Replacements, unsigned>( 2005 const Environment &)> 2006 AnalyzerPass; 2007 SmallVector<AnalyzerPass, 4> Passes; 2008 2009 if (Style.Language == FormatStyle::LK_Cpp) { 2010 if (Style.FixNamespaceComments) 2011 Passes.emplace_back([&](const Environment &Env) { 2012 return NamespaceEndCommentsFixer(Env, Expanded).process(); 2013 }); 2014 2015 if (Style.SortUsingDeclarations) 2016 Passes.emplace_back([&](const Environment &Env) { 2017 return UsingDeclarationsSorter(Env, Expanded).process(); 2018 }); 2019 } 2020 2021 if (Style.Language == FormatStyle::LK_JavaScript && 2022 Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) 2023 Passes.emplace_back([&](const Environment &Env) { 2024 return JavaScriptRequoter(Env, Expanded).process(); 2025 }); 2026 2027 Passes.emplace_back([&](const Environment &Env) { 2028 return Formatter(Env, Expanded, Status).process(); 2029 }); 2030 2031 std::unique_ptr<Environment> Env = Environment::CreateVirtualEnvironment( 2032 Code, FileName, Ranges, FirstStartColumn, NextStartColumn, 2033 LastStartColumn); 2034 llvm::Optional<std::string> CurrentCode = None; 2035 tooling::Replacements Fixes; 2036 unsigned Penalty = 0; 2037 for (size_t I = 0, E = Passes.size(); I < E; ++I) { 2038 std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env); 2039 auto NewCode = applyAllReplacements( 2040 CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first); 2041 if (NewCode) { 2042 Fixes = Fixes.merge(PassFixes.first); 2043 Penalty += PassFixes.second; 2044 if (I + 1 < E) { 2045 CurrentCode = std::move(*NewCode); 2046 Env = Environment::CreateVirtualEnvironment( 2047 *CurrentCode, FileName, 2048 tooling::calculateRangesAfterReplacements(Fixes, Ranges), 2049 FirstStartColumn, NextStartColumn, LastStartColumn); 2050 } 2051 } 2052 } 2053 2054 return {Fixes, Penalty}; 2055 } 2056 } // namespace internal 2057 2058 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 2059 ArrayRef<tooling::Range> Ranges, 2060 StringRef FileName, 2061 FormattingAttemptStatus *Status) { 2062 return internal::reformat(Style, Code, Ranges, 2063 /*FirstStartColumn=*/0, 2064 /*NextStartColumn=*/0, 2065 /*LastStartColumn=*/0, FileName, Status) 2066 .first; 2067 } 2068 2069 tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, 2070 ArrayRef<tooling::Range> Ranges, 2071 StringRef FileName) { 2072 // cleanups only apply to C++ (they mostly concern ctor commas etc.) 2073 if (Style.Language != FormatStyle::LK_Cpp) 2074 return tooling::Replacements(); 2075 std::unique_ptr<Environment> Env = 2076 Environment::CreateVirtualEnvironment(Code, FileName, Ranges); 2077 Cleaner Clean(*Env, Style); 2078 return Clean.process().first; 2079 } 2080 2081 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 2082 ArrayRef<tooling::Range> Ranges, 2083 StringRef FileName, bool *IncompleteFormat) { 2084 FormattingAttemptStatus Status; 2085 auto Result = reformat(Style, Code, Ranges, FileName, &Status); 2086 if (!Status.FormatComplete) 2087 *IncompleteFormat = true; 2088 return Result; 2089 } 2090 2091 tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, 2092 StringRef Code, 2093 ArrayRef<tooling::Range> Ranges, 2094 StringRef FileName) { 2095 std::unique_ptr<Environment> Env = 2096 Environment::CreateVirtualEnvironment(Code, FileName, Ranges); 2097 NamespaceEndCommentsFixer Fix(*Env, Style); 2098 return Fix.process().first; 2099 } 2100 2101 tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, 2102 StringRef Code, 2103 ArrayRef<tooling::Range> Ranges, 2104 StringRef FileName) { 2105 std::unique_ptr<Environment> Env = 2106 Environment::CreateVirtualEnvironment(Code, FileName, Ranges); 2107 UsingDeclarationsSorter Sorter(*Env, Style); 2108 return Sorter.process().first; 2109 } 2110 2111 LangOptions getFormattingLangOpts(const FormatStyle &Style) { 2112 LangOptions LangOpts; 2113 LangOpts.CPlusPlus = 1; 2114 LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2115 LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2116 LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2117 LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2118 LangOpts.LineComment = 1; 2119 bool AlternativeOperators = Style.isCpp(); 2120 LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0; 2121 LangOpts.Bool = 1; 2122 LangOpts.ObjC1 = 1; 2123 LangOpts.ObjC2 = 1; 2124 LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally. 2125 LangOpts.DeclSpecKeyword = 1; // To get __declspec. 2126 return LangOpts; 2127 } 2128 2129 const char *StyleOptionHelpDescription = 2130 "Coding style, currently supports:\n" 2131 " LLVM, Google, Chromium, Mozilla, WebKit.\n" 2132 "Use -style=file to load style configuration from\n" 2133 ".clang-format file located in one of the parent\n" 2134 "directories of the source file (or current\n" 2135 "directory for stdin).\n" 2136 "Use -style=\"{key: value, ...}\" to set specific\n" 2137 "parameters, e.g.:\n" 2138 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; 2139 2140 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) { 2141 if (FileName.endswith(".java")) 2142 return FormatStyle::LK_Java; 2143 if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts")) 2144 return FormatStyle::LK_JavaScript; // JavaScript or TypeScript. 2145 if (FileName.endswith(".m") || FileName.endswith(".mm")) 2146 return FormatStyle::LK_ObjC; 2147 if (FileName.endswith_lower(".proto") || 2148 FileName.endswith_lower(".protodevel")) 2149 return FormatStyle::LK_Proto; 2150 if (FileName.endswith_lower(".textpb") || 2151 FileName.endswith_lower(".pb.txt") || 2152 FileName.endswith_lower(".textproto") || 2153 FileName.endswith_lower(".asciipb")) 2154 return FormatStyle::LK_TextProto; 2155 if (FileName.endswith_lower(".td")) 2156 return FormatStyle::LK_TableGen; 2157 return FormatStyle::LK_Cpp; 2158 } 2159 2160 llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName, 2161 StringRef FallbackStyleName, 2162 StringRef Code, vfs::FileSystem *FS) { 2163 if (!FS) { 2164 FS = vfs::getRealFileSystem().get(); 2165 } 2166 FormatStyle Style = getLLVMStyle(); 2167 Style.Language = getLanguageByFileName(FileName); 2168 2169 // This is a very crude detection of whether a header contains ObjC code that 2170 // should be improved over time and probably be done on tokens, not one the 2171 // bare content of the file. 2172 if (Style.Language == FormatStyle::LK_Cpp && FileName.endswith(".h") && 2173 (Code.contains("\n- (") || Code.contains("\n+ (") || 2174 Code.contains("\n@end\n") || Code.contains("\n@end ") || 2175 Code.endswith("@end"))) 2176 Style.Language = FormatStyle::LK_ObjC; 2177 2178 FormatStyle FallbackStyle = getNoStyle(); 2179 if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle)) 2180 return make_string_error("Invalid fallback style \"" + FallbackStyleName); 2181 2182 if (StyleName.startswith("{")) { 2183 // Parse YAML/JSON style from the command line. 2184 if (std::error_code ec = parseConfiguration(StyleName, &Style)) 2185 return make_string_error("Error parsing -style: " + ec.message()); 2186 return Style; 2187 } 2188 2189 if (!StyleName.equals_lower("file")) { 2190 if (!getPredefinedStyle(StyleName, Style.Language, &Style)) 2191 return make_string_error("Invalid value for -style"); 2192 return Style; 2193 } 2194 2195 // Look for .clang-format/_clang-format file in the file's parent directories. 2196 SmallString<128> UnsuitableConfigFiles; 2197 SmallString<128> Path(FileName); 2198 if (std::error_code EC = FS->makeAbsolute(Path)) 2199 return make_string_error(EC.message()); 2200 2201 for (StringRef Directory = Path; !Directory.empty(); 2202 Directory = llvm::sys::path::parent_path(Directory)) { 2203 2204 auto Status = FS->status(Directory); 2205 if (!Status || 2206 Status->getType() != llvm::sys::fs::file_type::directory_file) { 2207 continue; 2208 } 2209 2210 SmallString<128> ConfigFile(Directory); 2211 2212 llvm::sys::path::append(ConfigFile, ".clang-format"); 2213 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); 2214 2215 Status = FS->status(ConfigFile.str()); 2216 bool FoundConfigFile = 2217 Status && (Status->getType() == llvm::sys::fs::file_type::regular_file); 2218 if (!FoundConfigFile) { 2219 // Try _clang-format too, since dotfiles are not commonly used on Windows. 2220 ConfigFile = Directory; 2221 llvm::sys::path::append(ConfigFile, "_clang-format"); 2222 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); 2223 Status = FS->status(ConfigFile.str()); 2224 FoundConfigFile = Status && (Status->getType() == 2225 llvm::sys::fs::file_type::regular_file); 2226 } 2227 2228 if (FoundConfigFile) { 2229 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text = 2230 FS->getBufferForFile(ConfigFile.str()); 2231 if (std::error_code EC = Text.getError()) 2232 return make_string_error(EC.message()); 2233 if (std::error_code ec = 2234 parseConfiguration(Text.get()->getBuffer(), &Style)) { 2235 if (ec == ParseError::Unsuitable) { 2236 if (!UnsuitableConfigFiles.empty()) 2237 UnsuitableConfigFiles.append(", "); 2238 UnsuitableConfigFiles.append(ConfigFile); 2239 continue; 2240 } 2241 return make_string_error("Error reading " + ConfigFile + ": " + 2242 ec.message()); 2243 } 2244 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); 2245 return Style; 2246 } 2247 } 2248 if (!UnsuitableConfigFiles.empty()) 2249 return make_string_error("Configuration file(s) do(es) not support " + 2250 getLanguageName(Style.Language) + ": " + 2251 UnsuitableConfigFiles); 2252 return FallbackStyle; 2253 } 2254 2255 } // namespace format 2256 } // namespace clang 2257