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