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