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 "ContinuationIndenter.h" 17 #include "TokenAnnotator.h" 18 #include "UnwrappedLineParser.h" 19 #include "WhitespaceManager.h" 20 #include "clang/Basic/Diagnostic.h" 21 #include "clang/Basic/DiagnosticOptions.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Format/Format.h" 24 #include "clang/Lex/Lexer.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/Support/Allocator.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/YAMLTraits.h" 30 #include <queue> 31 #include <string> 32 33 #define DEBUG_TYPE "format-formatter" 34 35 using clang::format::FormatStyle; 36 37 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string) 38 39 namespace llvm { 40 namespace yaml { 41 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> { 42 static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) { 43 IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp); 44 IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript); 45 IO.enumCase(Value, "Proto", FormatStyle::LK_Proto); 46 } 47 }; 48 49 template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> { 50 static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) { 51 IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); 52 IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); 53 IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11); 54 IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); 55 IO.enumCase(Value, "Auto", FormatStyle::LS_Auto); 56 } 57 }; 58 59 template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> { 60 static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) { 61 IO.enumCase(Value, "Never", FormatStyle::UT_Never); 62 IO.enumCase(Value, "false", FormatStyle::UT_Never); 63 IO.enumCase(Value, "Always", FormatStyle::UT_Always); 64 IO.enumCase(Value, "true", FormatStyle::UT_Always); 65 IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation); 66 } 67 }; 68 69 template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> { 70 static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) { 71 IO.enumCase(Value, "None", FormatStyle::SFS_None); 72 IO.enumCase(Value, "false", FormatStyle::SFS_None); 73 IO.enumCase(Value, "All", FormatStyle::SFS_All); 74 IO.enumCase(Value, "true", FormatStyle::SFS_All); 75 IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); 76 } 77 }; 78 79 template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> { 80 static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) { 81 IO.enumCase(Value, "Attach", FormatStyle::BS_Attach); 82 IO.enumCase(Value, "Linux", FormatStyle::BS_Linux); 83 IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup); 84 IO.enumCase(Value, "Allman", FormatStyle::BS_Allman); 85 IO.enumCase(Value, "GNU", FormatStyle::BS_GNU); 86 } 87 }; 88 89 template <> 90 struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> { 91 static void enumeration(IO &IO, 92 FormatStyle::NamespaceIndentationKind &Value) { 93 IO.enumCase(Value, "None", FormatStyle::NI_None); 94 IO.enumCase(Value, "Inner", FormatStyle::NI_Inner); 95 IO.enumCase(Value, "All", FormatStyle::NI_All); 96 } 97 }; 98 99 template <> 100 struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> { 101 static void enumeration(IO &IO, 102 FormatStyle::PointerAlignmentStyle &Value) { 103 IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle); 104 IO.enumCase(Value, "Left", FormatStyle::PAS_Left); 105 IO.enumCase(Value, "Right", FormatStyle::PAS_Right); 106 107 // For backward compatibility. 108 IO.enumCase(Value, "true", FormatStyle::PAS_Left); 109 IO.enumCase(Value, "false", FormatStyle::PAS_Right); 110 } 111 }; 112 113 template <> 114 struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> { 115 static void enumeration(IO &IO, 116 FormatStyle::SpaceBeforeParensOptions &Value) { 117 IO.enumCase(Value, "Never", FormatStyle::SBPO_Never); 118 IO.enumCase(Value, "ControlStatements", 119 FormatStyle::SBPO_ControlStatements); 120 IO.enumCase(Value, "Always", FormatStyle::SBPO_Always); 121 122 // For backward compatibility. 123 IO.enumCase(Value, "false", FormatStyle::SBPO_Never); 124 IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements); 125 } 126 }; 127 128 template <> struct MappingTraits<FormatStyle> { 129 static void mapping(IO &IO, FormatStyle &Style) { 130 // When reading, read the language first, we need it for getPredefinedStyle. 131 IO.mapOptional("Language", Style.Language); 132 133 if (IO.outputting()) { 134 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", 135 "Mozilla", "WebKit", "GNU" }; 136 ArrayRef<StringRef> Styles(StylesArray); 137 for (size_t i = 0, e = Styles.size(); i < e; ++i) { 138 StringRef StyleName(Styles[i]); 139 FormatStyle PredefinedStyle; 140 if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) && 141 Style == PredefinedStyle) { 142 IO.mapOptional("# BasedOnStyle", StyleName); 143 break; 144 } 145 } 146 } else { 147 StringRef BasedOnStyle; 148 IO.mapOptional("BasedOnStyle", BasedOnStyle); 149 if (!BasedOnStyle.empty()) { 150 FormatStyle::LanguageKind OldLanguage = Style.Language; 151 FormatStyle::LanguageKind Language = 152 ((FormatStyle *)IO.getContext())->Language; 153 if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) { 154 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle)); 155 return; 156 } 157 Style.Language = OldLanguage; 158 } 159 } 160 161 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); 162 IO.mapOptional("ConstructorInitializerIndentWidth", 163 Style.ConstructorInitializerIndentWidth); 164 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft); 165 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); 166 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", 167 Style.AllowAllParametersOfDeclarationOnNextLine); 168 IO.mapOptional("AllowShortBlocksOnASingleLine", 169 Style.AllowShortBlocksOnASingleLine); 170 IO.mapOptional("AllowShortIfStatementsOnASingleLine", 171 Style.AllowShortIfStatementsOnASingleLine); 172 IO.mapOptional("AllowShortLoopsOnASingleLine", 173 Style.AllowShortLoopsOnASingleLine); 174 IO.mapOptional("AllowShortFunctionsOnASingleLine", 175 Style.AllowShortFunctionsOnASingleLine); 176 IO.mapOptional("AlwaysBreakAfterDefinitionReturnType", 177 Style.AlwaysBreakAfterDefinitionReturnType); 178 IO.mapOptional("AlwaysBreakTemplateDeclarations", 179 Style.AlwaysBreakTemplateDeclarations); 180 IO.mapOptional("AlwaysBreakBeforeMultilineStrings", 181 Style.AlwaysBreakBeforeMultilineStrings); 182 IO.mapOptional("BreakBeforeBinaryOperators", 183 Style.BreakBeforeBinaryOperators); 184 IO.mapOptional("BreakBeforeTernaryOperators", 185 Style.BreakBeforeTernaryOperators); 186 IO.mapOptional("BreakConstructorInitializersBeforeComma", 187 Style.BreakConstructorInitializersBeforeComma); 188 IO.mapOptional("BinPackParameters", Style.BinPackParameters); 189 IO.mapOptional("ColumnLimit", Style.ColumnLimit); 190 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", 191 Style.ConstructorInitializerAllOnOneLineOrOnePerLine); 192 IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment); 193 IO.mapOptional("ExperimentalAutoDetectBinPacking", 194 Style.ExperimentalAutoDetectBinPacking); 195 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); 196 IO.mapOptional("IndentWrappedFunctionNames", 197 Style.IndentWrappedFunctionNames); 198 IO.mapOptional("IndentFunctionDeclarationAfterType", 199 Style.IndentWrappedFunctionNames); 200 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); 201 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks", 202 Style.KeepEmptyLinesAtTheStartOfBlocks); 203 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation); 204 IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); 205 IO.mapOptional("ObjCSpaceBeforeProtocolList", 206 Style.ObjCSpaceBeforeProtocolList); 207 IO.mapOptional("PenaltyBreakBeforeFirstCallParameter", 208 Style.PenaltyBreakBeforeFirstCallParameter); 209 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment); 210 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString); 211 IO.mapOptional("PenaltyBreakFirstLessLess", 212 Style.PenaltyBreakFirstLessLess); 213 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); 214 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", 215 Style.PenaltyReturnTypeOnItsOwnLine); 216 IO.mapOptional("PointerAlignment", Style.PointerAlignment); 217 IO.mapOptional("SpacesBeforeTrailingComments", 218 Style.SpacesBeforeTrailingComments); 219 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle); 220 IO.mapOptional("Standard", Style.Standard); 221 IO.mapOptional("IndentWidth", Style.IndentWidth); 222 IO.mapOptional("TabWidth", Style.TabWidth); 223 IO.mapOptional("UseTab", Style.UseTab); 224 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces); 225 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses); 226 IO.mapOptional("SpacesInAngles", Style.SpacesInAngles); 227 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses); 228 IO.mapOptional("SpacesInCStyleCastParentheses", 229 Style.SpacesInCStyleCastParentheses); 230 IO.mapOptional("SpacesInContainerLiterals", 231 Style.SpacesInContainerLiterals); 232 IO.mapOptional("SpaceBeforeAssignmentOperators", 233 Style.SpaceBeforeAssignmentOperators); 234 IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth); 235 IO.mapOptional("CommentPragmas", Style.CommentPragmas); 236 IO.mapOptional("ForEachMacros", Style.ForEachMacros); 237 238 // For backward compatibility. 239 if (!IO.outputting()) { 240 IO.mapOptional("SpaceAfterControlStatementKeyword", 241 Style.SpaceBeforeParens); 242 IO.mapOptional("PointerBindsToType", Style.PointerAlignment); 243 IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment); 244 } 245 IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens); 246 IO.mapOptional("DisableFormat", Style.DisableFormat); 247 } 248 }; 249 250 // Allows to read vector<FormatStyle> while keeping default values. 251 // IO.getContext() should contain a pointer to the FormatStyle structure, that 252 // will be used to get default values for missing keys. 253 // If the first element has no Language specified, it will be treated as the 254 // default one for the following elements. 255 template <> struct DocumentListTraits<std::vector<FormatStyle> > { 256 static size_t size(IO &IO, std::vector<FormatStyle> &Seq) { 257 return Seq.size(); 258 } 259 static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq, 260 size_t Index) { 261 if (Index >= Seq.size()) { 262 assert(Index == Seq.size()); 263 FormatStyle Template; 264 if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) { 265 Template = Seq[0]; 266 } else { 267 Template = *((const FormatStyle *)IO.getContext()); 268 Template.Language = FormatStyle::LK_None; 269 } 270 Seq.resize(Index + 1, Template); 271 } 272 return Seq[Index]; 273 } 274 }; 275 } 276 } 277 278 namespace clang { 279 namespace format { 280 281 const std::error_category &getParseCategory() { 282 static ParseErrorCategory C; 283 return C; 284 } 285 std::error_code make_error_code(ParseError e) { 286 return std::error_code(static_cast<int>(e), getParseCategory()); 287 } 288 289 const char *ParseErrorCategory::name() const LLVM_NOEXCEPT { 290 return "clang-format.parse_error"; 291 } 292 293 std::string ParseErrorCategory::message(int EV) const { 294 switch (static_cast<ParseError>(EV)) { 295 case ParseError::Success: 296 return "Success"; 297 case ParseError::Error: 298 return "Invalid argument"; 299 case ParseError::Unsuitable: 300 return "Unsuitable"; 301 } 302 llvm_unreachable("unexpected parse error"); 303 } 304 305 FormatStyle getLLVMStyle() { 306 FormatStyle LLVMStyle; 307 LLVMStyle.Language = FormatStyle::LK_Cpp; 308 LLVMStyle.AccessModifierOffset = -2; 309 LLVMStyle.AlignEscapedNewlinesLeft = false; 310 LLVMStyle.AlignTrailingComments = true; 311 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; 312 LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 313 LLVMStyle.AllowShortBlocksOnASingleLine = false; 314 LLVMStyle.AllowShortIfStatementsOnASingleLine = false; 315 LLVMStyle.AllowShortLoopsOnASingleLine = false; 316 LLVMStyle.AlwaysBreakAfterDefinitionReturnType = false; 317 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false; 318 LLVMStyle.AlwaysBreakTemplateDeclarations = false; 319 LLVMStyle.BinPackParameters = true; 320 LLVMStyle.BreakBeforeBinaryOperators = false; 321 LLVMStyle.BreakBeforeTernaryOperators = true; 322 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; 323 LLVMStyle.BreakConstructorInitializersBeforeComma = false; 324 LLVMStyle.ColumnLimit = 80; 325 LLVMStyle.CommentPragmas = "^ IWYU pragma:"; 326 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 327 LLVMStyle.ConstructorInitializerIndentWidth = 4; 328 LLVMStyle.ContinuationIndentWidth = 4; 329 LLVMStyle.Cpp11BracedListStyle = true; 330 LLVMStyle.DerivePointerAlignment = false; 331 LLVMStyle.ExperimentalAutoDetectBinPacking = false; 332 LLVMStyle.ForEachMacros.push_back("foreach"); 333 LLVMStyle.ForEachMacros.push_back("Q_FOREACH"); 334 LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH"); 335 LLVMStyle.IndentCaseLabels = false; 336 LLVMStyle.IndentWrappedFunctionNames = false; 337 LLVMStyle.IndentWidth = 2; 338 LLVMStyle.TabWidth = 8; 339 LLVMStyle.MaxEmptyLinesToKeep = 1; 340 LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true; 341 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None; 342 LLVMStyle.ObjCSpaceAfterProperty = false; 343 LLVMStyle.ObjCSpaceBeforeProtocolList = true; 344 LLVMStyle.PointerAlignment = FormatStyle::PAS_Right; 345 LLVMStyle.SpacesBeforeTrailingComments = 1; 346 LLVMStyle.Standard = FormatStyle::LS_Cpp11; 347 LLVMStyle.UseTab = FormatStyle::UT_Never; 348 LLVMStyle.SpacesInParentheses = false; 349 LLVMStyle.SpaceInEmptyParentheses = false; 350 LLVMStyle.SpacesInContainerLiterals = true; 351 LLVMStyle.SpacesInCStyleCastParentheses = false; 352 LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements; 353 LLVMStyle.SpaceBeforeAssignmentOperators = true; 354 LLVMStyle.SpacesInAngles = false; 355 356 LLVMStyle.PenaltyBreakComment = 300; 357 LLVMStyle.PenaltyBreakFirstLessLess = 120; 358 LLVMStyle.PenaltyBreakString = 1000; 359 LLVMStyle.PenaltyExcessCharacter = 1000000; 360 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60; 361 LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19; 362 363 LLVMStyle.DisableFormat = false; 364 365 return LLVMStyle; 366 } 367 368 FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { 369 FormatStyle GoogleStyle = getLLVMStyle(); 370 GoogleStyle.Language = Language; 371 372 GoogleStyle.AccessModifierOffset = -1; 373 GoogleStyle.AlignEscapedNewlinesLeft = true; 374 GoogleStyle.AllowShortIfStatementsOnASingleLine = true; 375 GoogleStyle.AllowShortLoopsOnASingleLine = true; 376 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; 377 GoogleStyle.AlwaysBreakTemplateDeclarations = true; 378 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 379 GoogleStyle.DerivePointerAlignment = true; 380 GoogleStyle.IndentCaseLabels = true; 381 GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 382 GoogleStyle.ObjCSpaceAfterProperty = false; 383 GoogleStyle.ObjCSpaceBeforeProtocolList = false; 384 GoogleStyle.PointerAlignment = FormatStyle::PAS_Left; 385 GoogleStyle.SpacesBeforeTrailingComments = 2; 386 GoogleStyle.Standard = FormatStyle::LS_Auto; 387 388 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; 389 GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1; 390 391 if (Language == FormatStyle::LK_JavaScript) { 392 GoogleStyle.BreakBeforeTernaryOperators = false; 393 GoogleStyle.MaxEmptyLinesToKeep = 3; 394 GoogleStyle.SpacesInContainerLiterals = false; 395 } else if (Language == FormatStyle::LK_Proto) { 396 GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 397 GoogleStyle.SpacesInContainerLiterals = false; 398 } 399 400 return GoogleStyle; 401 } 402 403 FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) { 404 FormatStyle ChromiumStyle = getGoogleStyle(Language); 405 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; 406 ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 407 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; 408 ChromiumStyle.AllowShortLoopsOnASingleLine = false; 409 ChromiumStyle.BinPackParameters = false; 410 ChromiumStyle.DerivePointerAlignment = false; 411 ChromiumStyle.Standard = FormatStyle::LS_Cpp03; 412 return ChromiumStyle; 413 } 414 415 FormatStyle getMozillaStyle() { 416 FormatStyle MozillaStyle = getLLVMStyle(); 417 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; 418 MozillaStyle.Cpp11BracedListStyle = false; 419 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 420 MozillaStyle.DerivePointerAlignment = true; 421 MozillaStyle.IndentCaseLabels = true; 422 MozillaStyle.ObjCSpaceAfterProperty = true; 423 MozillaStyle.ObjCSpaceBeforeProtocolList = false; 424 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; 425 MozillaStyle.PointerAlignment = FormatStyle::PAS_Left; 426 MozillaStyle.Standard = FormatStyle::LS_Cpp03; 427 return MozillaStyle; 428 } 429 430 FormatStyle getWebKitStyle() { 431 FormatStyle Style = getLLVMStyle(); 432 Style.AccessModifierOffset = -4; 433 Style.AlignTrailingComments = false; 434 Style.BreakBeforeBinaryOperators = true; 435 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 436 Style.BreakConstructorInitializersBeforeComma = true; 437 Style.Cpp11BracedListStyle = false; 438 Style.ColumnLimit = 0; 439 Style.IndentWidth = 4; 440 Style.NamespaceIndentation = FormatStyle::NI_Inner; 441 Style.ObjCSpaceAfterProperty = true; 442 Style.PointerAlignment = FormatStyle::PAS_Left; 443 Style.Standard = FormatStyle::LS_Cpp03; 444 return Style; 445 } 446 447 FormatStyle getGNUStyle() { 448 FormatStyle Style = getLLVMStyle(); 449 Style.AlwaysBreakAfterDefinitionReturnType = true; 450 Style.BreakBeforeBinaryOperators = true; 451 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 452 Style.BreakBeforeTernaryOperators = true; 453 Style.Cpp11BracedListStyle = false; 454 Style.ColumnLimit = 79; 455 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 456 Style.Standard = FormatStyle::LS_Cpp03; 457 return Style; 458 } 459 460 FormatStyle getNoStyle() { 461 FormatStyle NoStyle = getLLVMStyle(); 462 NoStyle.DisableFormat = true; 463 return NoStyle; 464 } 465 466 bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, 467 FormatStyle *Style) { 468 if (Name.equals_lower("llvm")) { 469 *Style = getLLVMStyle(); 470 } else if (Name.equals_lower("chromium")) { 471 *Style = getChromiumStyle(Language); 472 } else if (Name.equals_lower("mozilla")) { 473 *Style = getMozillaStyle(); 474 } else if (Name.equals_lower("google")) { 475 *Style = getGoogleStyle(Language); 476 } else if (Name.equals_lower("webkit")) { 477 *Style = getWebKitStyle(); 478 } else if (Name.equals_lower("gnu")) { 479 *Style = getGNUStyle(); 480 } else if (Name.equals_lower("none")) { 481 *Style = getNoStyle(); 482 } else { 483 return false; 484 } 485 486 Style->Language = Language; 487 return true; 488 } 489 490 std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { 491 assert(Style); 492 FormatStyle::LanguageKind Language = Style->Language; 493 assert(Language != FormatStyle::LK_None); 494 if (Text.trim().empty()) 495 return make_error_code(ParseError::Error); 496 497 std::vector<FormatStyle> Styles; 498 llvm::yaml::Input Input(Text); 499 // DocumentListTraits<vector<FormatStyle>> uses the context to get default 500 // values for the fields, keys for which are missing from the configuration. 501 // Mapping also uses the context to get the language to find the correct 502 // base style. 503 Input.setContext(Style); 504 Input >> Styles; 505 if (Input.error()) 506 return Input.error(); 507 508 for (unsigned i = 0; i < Styles.size(); ++i) { 509 // Ensures that only the first configuration can skip the Language option. 510 if (Styles[i].Language == FormatStyle::LK_None && i != 0) 511 return make_error_code(ParseError::Error); 512 // Ensure that each language is configured at most once. 513 for (unsigned j = 0; j < i; ++j) { 514 if (Styles[i].Language == Styles[j].Language) { 515 DEBUG(llvm::dbgs() 516 << "Duplicate languages in the config file on positions " << j 517 << " and " << i << "\n"); 518 return make_error_code(ParseError::Error); 519 } 520 } 521 } 522 // Look for a suitable configuration starting from the end, so we can 523 // find the configuration for the specific language first, and the default 524 // configuration (which can only be at slot 0) after it. 525 for (int i = Styles.size() - 1; i >= 0; --i) { 526 if (Styles[i].Language == Language || 527 Styles[i].Language == FormatStyle::LK_None) { 528 *Style = Styles[i]; 529 Style->Language = Language; 530 return make_error_code(ParseError::Success); 531 } 532 } 533 return make_error_code(ParseError::Unsuitable); 534 } 535 536 std::string configurationAsText(const FormatStyle &Style) { 537 std::string Text; 538 llvm::raw_string_ostream Stream(Text); 539 llvm::yaml::Output Output(Stream); 540 // We use the same mapping method for input and output, so we need a non-const 541 // reference here. 542 FormatStyle NonConstStyle = Style; 543 Output << NonConstStyle; 544 return Stream.str(); 545 } 546 547 namespace { 548 549 class NoColumnLimitFormatter { 550 public: 551 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {} 552 553 /// \brief Formats the line starting at \p State, simply keeping all of the 554 /// input's line breaking decisions. 555 void format(unsigned FirstIndent, const AnnotatedLine *Line) { 556 LineState State = 557 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false); 558 while (State.NextToken) { 559 bool Newline = 560 Indenter->mustBreak(State) || 561 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 562 Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 563 } 564 } 565 566 private: 567 ContinuationIndenter *Indenter; 568 }; 569 570 class LineJoiner { 571 public: 572 LineJoiner(const FormatStyle &Style) : Style(Style) {} 573 574 /// \brief Calculates how many lines can be merged into 1 starting at \p I. 575 unsigned 576 tryFitMultipleLinesInOne(unsigned Indent, 577 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 578 SmallVectorImpl<AnnotatedLine *>::const_iterator E) { 579 // We can never merge stuff if there are trailing line comments. 580 const AnnotatedLine *TheLine = *I; 581 if (TheLine->Last->Type == TT_LineComment) 582 return 0; 583 584 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) 585 return 0; 586 587 unsigned Limit = 588 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; 589 // If we already exceed the column limit, we set 'Limit' to 0. The different 590 // tryMerge..() functions can then decide whether to still do merging. 591 Limit = TheLine->Last->TotalLength > Limit 592 ? 0 593 : Limit - TheLine->Last->TotalLength; 594 595 if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) 596 return 0; 597 598 // FIXME: TheLine->Level != 0 might or might not be the right check to do. 599 // If necessary, change to something smarter. 600 bool MergeShortFunctions = 601 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || 602 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline && 603 TheLine->Level != 0); 604 605 if (TheLine->Last->Type == TT_FunctionLBrace && 606 TheLine->First != TheLine->Last) { 607 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; 608 } 609 if (TheLine->Last->is(tok::l_brace)) { 610 return Style.BreakBeforeBraces == FormatStyle::BS_Attach 611 ? tryMergeSimpleBlock(I, E, Limit) 612 : 0; 613 } 614 if (I[1]->First->Type == TT_FunctionLBrace && 615 Style.BreakBeforeBraces != FormatStyle::BS_Attach) { 616 // Check for Limit <= 2 to account for the " {". 617 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) 618 return 0; 619 Limit -= 2; 620 621 unsigned MergedLines = 0; 622 if (MergeShortFunctions) { 623 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 624 // If we managed to merge the block, count the function header, which is 625 // on a separate line. 626 if (MergedLines > 0) 627 ++MergedLines; 628 } 629 return MergedLines; 630 } 631 if (TheLine->First->is(tok::kw_if)) { 632 return Style.AllowShortIfStatementsOnASingleLine 633 ? tryMergeSimpleControlStatement(I, E, Limit) 634 : 0; 635 } 636 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { 637 return Style.AllowShortLoopsOnASingleLine 638 ? tryMergeSimpleControlStatement(I, E, Limit) 639 : 0; 640 } 641 if (TheLine->InPPDirective && 642 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { 643 return tryMergeSimplePPDirective(I, E, Limit); 644 } 645 return 0; 646 } 647 648 private: 649 unsigned 650 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 651 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 652 unsigned Limit) { 653 if (Limit == 0) 654 return 0; 655 if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline) 656 return 0; 657 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) 658 return 0; 659 if (1 + I[1]->Last->TotalLength > Limit) 660 return 0; 661 return 1; 662 } 663 664 unsigned tryMergeSimpleControlStatement( 665 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 666 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 667 if (Limit == 0) 668 return 0; 669 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman || 670 Style.BreakBeforeBraces == FormatStyle::BS_GNU) && 671 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine)) 672 return 0; 673 if (I[1]->InPPDirective != (*I)->InPPDirective || 674 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) 675 return 0; 676 Limit = limitConsideringMacros(I + 1, E, Limit); 677 AnnotatedLine &Line = **I; 678 if (Line.Last->isNot(tok::r_paren)) 679 return 0; 680 if (1 + I[1]->Last->TotalLength > Limit) 681 return 0; 682 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, 683 tok::kw_while) || 684 I[1]->First->Type == TT_LineComment) 685 return 0; 686 // Only inline simple if's (no nested if or else). 687 if (I + 2 != E && Line.First->is(tok::kw_if) && 688 I[2]->First->is(tok::kw_else)) 689 return 0; 690 return 1; 691 } 692 693 unsigned 694 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 695 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 696 unsigned Limit) { 697 AnnotatedLine &Line = **I; 698 699 // Don't merge ObjC @ keywords and methods. 700 if (Line.First->isOneOf(tok::at, tok::minus, tok::plus)) 701 return 0; 702 703 // Check that the current line allows merging. This depends on whether we 704 // are in a control flow statements as well as several style flags. 705 if (Line.First->isOneOf(tok::kw_else, tok::kw_case)) 706 return 0; 707 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, 708 tok::kw_catch, tok::kw_for, tok::r_brace)) { 709 if (!Style.AllowShortBlocksOnASingleLine) 710 return 0; 711 if (!Style.AllowShortIfStatementsOnASingleLine && 712 Line.First->is(tok::kw_if)) 713 return 0; 714 if (!Style.AllowShortLoopsOnASingleLine && 715 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for)) 716 return 0; 717 // FIXME: Consider an option to allow short exception handling clauses on 718 // a single line. 719 if (Line.First->isOneOf(tok::kw_try, tok::kw_catch)) 720 return 0; 721 } 722 723 FormatToken *Tok = I[1]->First; 724 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && 725 (Tok->getNextNonComment() == nullptr || 726 Tok->getNextNonComment()->is(tok::semi))) { 727 // We merge empty blocks even if the line exceeds the column limit. 728 Tok->SpacesRequiredBefore = 0; 729 Tok->CanBreakBefore = true; 730 return 1; 731 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) { 732 // We don't merge short records. 733 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct)) 734 return 0; 735 736 // Check that we still have three lines and they fit into the limit. 737 if (I + 2 == E || I[2]->Type == LT_Invalid) 738 return 0; 739 Limit = limitConsideringMacros(I + 2, E, Limit); 740 741 if (!nextTwoLinesFitInto(I, Limit)) 742 return 0; 743 744 // Second, check that the next line does not contain any braces - if it 745 // does, readability declines when putting it into a single line. 746 if (I[1]->Last->Type == TT_LineComment) 747 return 0; 748 do { 749 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit) 750 return 0; 751 Tok = Tok->Next; 752 } while (Tok); 753 754 // Last, check that the third line starts with a closing brace. 755 Tok = I[2]->First; 756 if (Tok->isNot(tok::r_brace)) 757 return 0; 758 759 return 2; 760 } 761 return 0; 762 } 763 764 /// Returns the modified column limit for \p I if it is inside a macro and 765 /// needs a trailing '\'. 766 unsigned 767 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 768 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 769 unsigned Limit) { 770 if (I[0]->InPPDirective && I + 1 != E && 771 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { 772 return Limit < 2 ? 0 : Limit - 2; 773 } 774 return Limit; 775 } 776 777 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 778 unsigned Limit) { 779 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) 780 return false; 781 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; 782 } 783 784 bool containsMustBreak(const AnnotatedLine *Line) { 785 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 786 if (Tok->MustBreakBefore) 787 return true; 788 } 789 return false; 790 } 791 792 const FormatStyle &Style; 793 }; 794 795 class UnwrappedLineFormatter { 796 public: 797 UnwrappedLineFormatter(ContinuationIndenter *Indenter, 798 WhitespaceManager *Whitespaces, 799 const FormatStyle &Style) 800 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), 801 Joiner(Style) {} 802 803 unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun, 804 int AdditionalIndent = 0, bool FixBadIndentation = false) { 805 // Try to look up already computed penalty in DryRun-mode. 806 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( 807 &Lines, AdditionalIndent); 808 auto CacheIt = PenaltyCache.find(CacheKey); 809 if (DryRun && CacheIt != PenaltyCache.end()) 810 return CacheIt->second; 811 812 assert(!Lines.empty()); 813 unsigned Penalty = 0; 814 std::vector<int> IndentForLevel; 815 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i) 816 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); 817 const AnnotatedLine *PreviousLine = nullptr; 818 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(), 819 E = Lines.end(); 820 I != E; ++I) { 821 const AnnotatedLine &TheLine = **I; 822 const FormatToken *FirstTok = TheLine.First; 823 int Offset = getIndentOffset(*FirstTok); 824 825 // Determine indent and try to merge multiple unwrapped lines. 826 unsigned Indent; 827 if (TheLine.InPPDirective) { 828 Indent = TheLine.Level * Style.IndentWidth; 829 } else { 830 while (IndentForLevel.size() <= TheLine.Level) 831 IndentForLevel.push_back(-1); 832 IndentForLevel.resize(TheLine.Level + 1); 833 Indent = getIndent(IndentForLevel, TheLine.Level); 834 } 835 unsigned LevelIndent = Indent; 836 if (static_cast<int>(Indent) + Offset >= 0) 837 Indent += Offset; 838 839 // Merge multiple lines if possible. 840 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E); 841 if (MergedLines > 0 && Style.ColumnLimit == 0) { 842 // Disallow line merging if there is a break at the start of one of the 843 // input lines. 844 for (unsigned i = 0; i < MergedLines; ++i) { 845 if (I[i + 1]->First->NewlinesBefore > 0) 846 MergedLines = 0; 847 } 848 } 849 if (!DryRun) { 850 for (unsigned i = 0; i < MergedLines; ++i) { 851 join(*I[i], *I[i + 1]); 852 } 853 } 854 I += MergedLines; 855 856 bool FixIndentation = 857 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn); 858 if (TheLine.First->is(tok::eof)) { 859 if (PreviousLine && PreviousLine->Affected && !DryRun) { 860 // Remove the file's trailing whitespace. 861 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u); 862 Whitespaces->replaceWhitespace(*TheLine.First, Newlines, 863 /*IndentLevel=*/0, /*Spaces=*/0, 864 /*TargetColumn=*/0); 865 } 866 } else if (TheLine.Type != LT_Invalid && 867 (TheLine.Affected || FixIndentation)) { 868 if (FirstTok->WhitespaceRange.isValid()) { 869 if (!DryRun) 870 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, 871 Indent, TheLine.InPPDirective); 872 } else { 873 Indent = LevelIndent = FirstTok->OriginalColumn; 874 } 875 876 // If everything fits on a single line, just put it there. 877 unsigned ColumnLimit = Style.ColumnLimit; 878 if (I + 1 != E) { 879 AnnotatedLine *NextLine = I[1]; 880 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline) 881 ColumnLimit = getColumnLimit(TheLine.InPPDirective); 882 } 883 884 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) { 885 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun); 886 while (State.NextToken) { 887 formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty); 888 Indenter->addTokenToState(State, /*Newline=*/false, DryRun); 889 } 890 } else if (Style.ColumnLimit == 0) { 891 // FIXME: Implement nested blocks for ColumnLimit = 0. 892 NoColumnLimitFormatter Formatter(Indenter); 893 if (!DryRun) 894 Formatter.format(Indent, &TheLine); 895 } else { 896 Penalty += format(TheLine, Indent, DryRun); 897 } 898 899 if (!TheLine.InPPDirective) 900 IndentForLevel[TheLine.Level] = LevelIndent; 901 } else if (TheLine.ChildrenAffected) { 902 format(TheLine.Children, DryRun); 903 } else { 904 // Format the first token if necessary, and notify the WhitespaceManager 905 // about the unchanged whitespace. 906 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) { 907 if (Tok == TheLine.First && 908 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) { 909 unsigned LevelIndent = Tok->OriginalColumn; 910 if (!DryRun) { 911 // Remove trailing whitespace of the previous line. 912 if ((PreviousLine && PreviousLine->Affected) || 913 TheLine.LeadingEmptyLinesAffected) { 914 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent, 915 TheLine.InPPDirective); 916 } else { 917 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 918 } 919 } 920 921 if (static_cast<int>(LevelIndent) - Offset >= 0) 922 LevelIndent -= Offset; 923 if (Tok->isNot(tok::comment) && !TheLine.InPPDirective) 924 IndentForLevel[TheLine.Level] = LevelIndent; 925 } else if (!DryRun) { 926 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 927 } 928 } 929 } 930 if (!DryRun) { 931 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) { 932 Tok->Finalized = true; 933 } 934 } 935 PreviousLine = *I; 936 } 937 PenaltyCache[CacheKey] = Penalty; 938 return Penalty; 939 } 940 941 private: 942 /// \brief Formats an \c AnnotatedLine and returns the penalty. 943 /// 944 /// If \p DryRun is \c false, directly applies the changes. 945 unsigned format(const AnnotatedLine &Line, unsigned FirstIndent, 946 bool DryRun) { 947 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); 948 949 // If the ObjC method declaration does not fit on a line, we should format 950 // it with one arg per line. 951 if (State.Line->Type == LT_ObjCMethodDecl) 952 State.Stack.back().BreakBeforeParameter = true; 953 954 // Find best solution in solution space. 955 return analyzeSolutionSpace(State, DryRun); 956 } 957 958 /// \brief An edge in the solution space from \c Previous->State to \c State, 959 /// inserting a newline dependent on the \c NewLine. 960 struct StateNode { 961 StateNode(const LineState &State, bool NewLine, StateNode *Previous) 962 : State(State), NewLine(NewLine), Previous(Previous) {} 963 LineState State; 964 bool NewLine; 965 StateNode *Previous; 966 }; 967 968 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. 969 /// 970 /// In case of equal penalties, we want to prefer states that were inserted 971 /// first. During state generation we make sure that we insert states first 972 /// that break the line as late as possible. 973 typedef std::pair<unsigned, unsigned> OrderedPenalty; 974 975 /// \brief An item in the prioritized BFS search queue. The \c StateNode's 976 /// \c State has the given \c OrderedPenalty. 977 typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 978 979 /// \brief The BFS queue type. 980 typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 981 std::greater<QueueItem> > QueueType; 982 983 /// \brief Get the offset of the line relatively to the level. 984 /// 985 /// For example, 'public:' labels in classes are offset by 1 or 2 986 /// characters to the left from their level. 987 int getIndentOffset(const FormatToken &RootToken) { 988 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier()) 989 return Style.AccessModifierOffset; 990 return 0; 991 } 992 993 /// \brief Add a new line and the required indent before the first Token 994 /// of the \c UnwrappedLine if there was no structural parsing error. 995 void formatFirstToken(FormatToken &RootToken, 996 const AnnotatedLine *PreviousLine, unsigned IndentLevel, 997 unsigned Indent, bool InPPDirective) { 998 unsigned Newlines = 999 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1000 // Remove empty lines before "}" where applicable. 1001 if (RootToken.is(tok::r_brace) && 1002 (!RootToken.Next || 1003 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) 1004 Newlines = std::min(Newlines, 1u); 1005 if (Newlines == 0 && !RootToken.IsFirst) 1006 Newlines = 1; 1007 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) 1008 Newlines = 0; 1009 1010 // Remove empty lines after "{". 1011 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && 1012 PreviousLine->Last->is(tok::l_brace) && 1013 PreviousLine->First->isNot(tok::kw_namespace)) 1014 Newlines = 1; 1015 1016 // Insert extra new line before access specifiers. 1017 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 1018 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) 1019 ++Newlines; 1020 1021 // Remove empty lines after access specifiers. 1022 if (PreviousLine && PreviousLine->First->isAccessSpecifier()) 1023 Newlines = std::min(1u, Newlines); 1024 1025 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent, 1026 Indent, InPPDirective && 1027 !RootToken.HasUnescapedNewline); 1028 } 1029 1030 /// \brief Get the indent of \p Level from \p IndentForLevel. 1031 /// 1032 /// \p IndentForLevel must contain the indent for the level \c l 1033 /// at \p IndentForLevel[l], or a value < 0 if the indent for 1034 /// that level is unknown. 1035 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) { 1036 if (IndentForLevel[Level] != -1) 1037 return IndentForLevel[Level]; 1038 if (Level == 0) 1039 return 0; 1040 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; 1041 } 1042 1043 void join(AnnotatedLine &A, const AnnotatedLine &B) { 1044 assert(!A.Last->Next); 1045 assert(!B.First->Previous); 1046 if (B.Affected) 1047 A.Affected = true; 1048 A.Last->Next = B.First; 1049 B.First->Previous = A.Last; 1050 B.First->CanBreakBefore = true; 1051 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 1052 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 1053 Tok->TotalLength += LengthA; 1054 A.Last = Tok; 1055 } 1056 } 1057 1058 unsigned getColumnLimit(bool InPPDirective) const { 1059 // In preprocessor directives reserve two chars for trailing " \" 1060 return Style.ColumnLimit - (InPPDirective ? 2 : 0); 1061 } 1062 1063 struct CompareLineStatePointers { 1064 bool operator()(LineState *obj1, LineState *obj2) const { 1065 return *obj1 < *obj2; 1066 } 1067 }; 1068 1069 /// \brief Analyze the entire solution space starting from \p InitialState. 1070 /// 1071 /// This implements a variant of Dijkstra's algorithm on the graph that spans 1072 /// the solution space (\c LineStates are the nodes). The algorithm tries to 1073 /// find the shortest path (the one with lowest penalty) from \p InitialState 1074 /// to a state where all tokens are placed. Returns the penalty. 1075 /// 1076 /// If \p DryRun is \c false, directly applies the changes. 1077 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) { 1078 std::set<LineState *, CompareLineStatePointers> Seen; 1079 1080 // Increasing count of \c StateNode items we have created. This is used to 1081 // create a deterministic order independent of the container. 1082 unsigned Count = 0; 1083 QueueType Queue; 1084 1085 // Insert start element into queue. 1086 StateNode *Node = 1087 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); 1088 Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 1089 ++Count; 1090 1091 unsigned Penalty = 0; 1092 1093 // While not empty, take first element and follow edges. 1094 while (!Queue.empty()) { 1095 Penalty = Queue.top().first.first; 1096 StateNode *Node = Queue.top().second; 1097 if (!Node->State.NextToken) { 1098 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); 1099 break; 1100 } 1101 Queue.pop(); 1102 1103 // Cut off the analysis of certain solutions if the analysis gets too 1104 // complex. See description of IgnoreStackForComparison. 1105 if (Count > 10000) 1106 Node->State.IgnoreStackForComparison = true; 1107 1108 if (!Seen.insert(&Node->State).second) 1109 // State already examined with lower penalty. 1110 continue; 1111 1112 FormatDecision LastFormat = Node->State.NextToken->Decision; 1113 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) 1114 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); 1115 if (LastFormat == FD_Unformatted || LastFormat == FD_Break) 1116 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); 1117 } 1118 1119 if (Queue.empty()) { 1120 // We were unable to find a solution, do nothing. 1121 // FIXME: Add diagnostic? 1122 DEBUG(llvm::dbgs() << "Could not find a solution.\n"); 1123 return 0; 1124 } 1125 1126 // Reconstruct the solution. 1127 if (!DryRun) 1128 reconstructPath(InitialState, Queue.top().second); 1129 1130 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); 1131 DEBUG(llvm::dbgs() << "---\n"); 1132 1133 return Penalty; 1134 } 1135 1136 void reconstructPath(LineState &State, StateNode *Current) { 1137 std::deque<StateNode *> Path; 1138 // We do not need a break before the initial token. 1139 while (Current->Previous) { 1140 Path.push_front(Current); 1141 Current = Current->Previous; 1142 } 1143 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); 1144 I != E; ++I) { 1145 unsigned Penalty = 0; 1146 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); 1147 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); 1148 1149 DEBUG({ 1150 if ((*I)->NewLine) { 1151 llvm::dbgs() << "Penalty for placing " 1152 << (*I)->Previous->State.NextToken->Tok.getName() << ": " 1153 << Penalty << "\n"; 1154 } 1155 }); 1156 } 1157 } 1158 1159 /// \brief Add the following state to the analysis queue \c Queue. 1160 /// 1161 /// Assume the current state is \p PreviousNode and has been reached with a 1162 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 1163 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 1164 bool NewLine, unsigned *Count, QueueType *Queue) { 1165 if (NewLine && !Indenter->canBreak(PreviousNode->State)) 1166 return; 1167 if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 1168 return; 1169 1170 StateNode *Node = new (Allocator.Allocate()) 1171 StateNode(PreviousNode->State, NewLine, PreviousNode); 1172 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 1173 return; 1174 1175 Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 1176 1177 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); 1178 ++(*Count); 1179 } 1180 1181 /// \brief If the \p State's next token is an r_brace closing a nested block, 1182 /// format the nested block before it. 1183 /// 1184 /// Returns \c true if all children could be placed successfully and adapts 1185 /// \p Penalty as well as \p State. If \p DryRun is false, also directly 1186 /// creates changes using \c Whitespaces. 1187 /// 1188 /// The crucial idea here is that children always get formatted upon 1189 /// encountering the closing brace right after the nested block. Now, if we 1190 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is 1191 /// \c false), the entire block has to be kept on the same line (which is only 1192 /// possible if it fits on the line, only contains a single statement, etc. 1193 /// 1194 /// If \p NewLine is true, we format the nested block on separate lines, i.e. 1195 /// break after the "{", format all lines with correct indentation and the put 1196 /// the closing "}" on yet another new line. 1197 /// 1198 /// This enables us to keep the simple structure of the 1199 /// \c UnwrappedLineFormatter, where we only have two options for each token: 1200 /// break or don't break. 1201 bool formatChildren(LineState &State, bool NewLine, bool DryRun, 1202 unsigned &Penalty) { 1203 FormatToken &Previous = *State.NextToken->Previous; 1204 const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); 1205 if (!LBrace || LBrace->isNot(tok::l_brace) || 1206 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0) 1207 // The previous token does not open a block. Nothing to do. We don't 1208 // assert so that we can simply call this function for all tokens. 1209 return true; 1210 1211 if (NewLine) { 1212 int AdditionalIndent = 1213 State.FirstIndent - State.Line->Level * Style.IndentWidth; 1214 if (State.Stack.size() < 2 || 1215 !State.Stack[State.Stack.size() - 2].JSFunctionInlined) { 1216 AdditionalIndent = State.Stack.back().Indent - 1217 Previous.Children[0]->Level * Style.IndentWidth; 1218 } 1219 1220 Penalty += format(Previous.Children, DryRun, AdditionalIndent, 1221 /*FixBadIndentation=*/true); 1222 return true; 1223 } 1224 1225 // Cannot merge multiple statements into a single line. 1226 if (Previous.Children.size() > 1) 1227 return false; 1228 1229 // Cannot merge into one line if this line ends on a comment. 1230 if (Previous.is(tok::comment)) 1231 return false; 1232 1233 // We can't put the closing "}" on a line with a trailing comment. 1234 if (Previous.Children[0]->Last->isTrailingComment()) 1235 return false; 1236 1237 // If the child line exceeds the column limit, we wouldn't want to merge it. 1238 // We add +2 for the trailing " }". 1239 if (Style.ColumnLimit > 0 && 1240 Previous.Children[0]->Last->TotalLength + State.Column + 2 > 1241 Style.ColumnLimit) 1242 return false; 1243 1244 if (!DryRun) { 1245 Whitespaces->replaceWhitespace( 1246 *Previous.Children[0]->First, 1247 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1, 1248 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); 1249 } 1250 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun); 1251 1252 State.Column += 1 + Previous.Children[0]->Last->TotalLength; 1253 return true; 1254 } 1255 1256 ContinuationIndenter *Indenter; 1257 WhitespaceManager *Whitespaces; 1258 FormatStyle Style; 1259 LineJoiner Joiner; 1260 1261 llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 1262 1263 // Cache to store the penalty of formatting a vector of AnnotatedLines 1264 // starting from a specific additional offset. Improves performance if there 1265 // are many nested blocks. 1266 std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>, 1267 unsigned> PenaltyCache; 1268 }; 1269 1270 class FormatTokenLexer { 1271 public: 1272 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style, 1273 encoding::Encoding Encoding) 1274 : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false), 1275 Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), 1276 Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding), 1277 FirstInLineIndex(0), FormattingDisabled(false) { 1278 Lex.SetKeepWhitespaceMode(true); 1279 1280 for (const std::string &ForEachMacro : Style.ForEachMacros) 1281 ForEachMacros.push_back(&IdentTable.get(ForEachMacro)); 1282 std::sort(ForEachMacros.begin(), ForEachMacros.end()); 1283 } 1284 1285 ArrayRef<FormatToken *> lex() { 1286 assert(Tokens.empty()); 1287 assert(FirstInLineIndex == 0); 1288 do { 1289 Tokens.push_back(getNextToken()); 1290 tryMergePreviousTokens(); 1291 if (Tokens.back()->NewlinesBefore > 0) 1292 FirstInLineIndex = Tokens.size() - 1; 1293 } while (Tokens.back()->Tok.isNot(tok::eof)); 1294 return Tokens; 1295 } 1296 1297 IdentifierTable &getIdentTable() { return IdentTable; } 1298 1299 private: 1300 void tryMergePreviousTokens() { 1301 if (tryMerge_TMacro()) 1302 return; 1303 if (tryMergeConflictMarkers()) 1304 return; 1305 1306 if (Style.Language == FormatStyle::LK_JavaScript) { 1307 if (tryMergeEscapeSequence()) 1308 return; 1309 if (tryMergeJSRegexLiteral()) 1310 return; 1311 1312 static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal }; 1313 static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal }; 1314 static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater, 1315 tok::greaterequal }; 1316 static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater }; 1317 // FIXME: We probably need to change token type to mimic operator with the 1318 // correct priority. 1319 if (tryMergeTokens(JSIdentity)) 1320 return; 1321 if (tryMergeTokens(JSNotIdentity)) 1322 return; 1323 if (tryMergeTokens(JSShiftEqual)) 1324 return; 1325 if (tryMergeTokens(JSRightArrow)) 1326 return; 1327 } 1328 } 1329 1330 bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) { 1331 if (Tokens.size() < Kinds.size()) 1332 return false; 1333 1334 SmallVectorImpl<FormatToken *>::const_iterator First = 1335 Tokens.end() - Kinds.size(); 1336 if (!First[0]->is(Kinds[0])) 1337 return false; 1338 unsigned AddLength = 0; 1339 for (unsigned i = 1; i < Kinds.size(); ++i) { 1340 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() != 1341 First[i]->WhitespaceRange.getEnd()) 1342 return false; 1343 AddLength += First[i]->TokenText.size(); 1344 } 1345 Tokens.resize(Tokens.size() - Kinds.size() + 1); 1346 First[0]->TokenText = StringRef(First[0]->TokenText.data(), 1347 First[0]->TokenText.size() + AddLength); 1348 First[0]->ColumnWidth += AddLength; 1349 return true; 1350 } 1351 1352 // Tries to merge an escape sequence, i.e. a "\\" and the following 1353 // character. Use e.g. inside JavaScript regex literals. 1354 bool tryMergeEscapeSequence() { 1355 if (Tokens.size() < 2) 1356 return false; 1357 FormatToken *Previous = Tokens[Tokens.size() - 2]; 1358 if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" || 1359 Tokens.back()->NewlinesBefore != 0) 1360 return false; 1361 Previous->ColumnWidth += Tokens.back()->ColumnWidth; 1362 StringRef Text = Previous->TokenText; 1363 Previous->TokenText = 1364 StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size()); 1365 Tokens.resize(Tokens.size() - 1); 1366 return true; 1367 } 1368 1369 // Try to determine whether the current token ends a JavaScript regex literal. 1370 // We heuristically assume that this is a regex literal if we find two 1371 // unescaped slashes on a line and the token before the first slash is one of 1372 // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by 1373 // a division. 1374 bool tryMergeJSRegexLiteral() { 1375 if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) || 1376 (Tokens[Tokens.size() - 2]->is(tok::unknown) && 1377 Tokens[Tokens.size() - 2]->TokenText == "\\")) 1378 return false; 1379 unsigned TokenCount = 0; 1380 unsigned LastColumn = Tokens.back()->OriginalColumn; 1381 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) { 1382 ++TokenCount; 1383 if (I[0]->is(tok::slash) && I + 1 != E && 1384 (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace, 1385 tok::exclaim, tok::l_square, tok::colon, tok::comma, 1386 tok::question, tok::kw_return) || 1387 I[1]->isBinaryOperator())) { 1388 Tokens.resize(Tokens.size() - TokenCount); 1389 Tokens.back()->Tok.setKind(tok::unknown); 1390 Tokens.back()->Type = TT_RegexLiteral; 1391 Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn; 1392 return true; 1393 } 1394 1395 // There can't be a newline inside a regex literal. 1396 if (I[0]->NewlinesBefore > 0) 1397 return false; 1398 } 1399 return false; 1400 } 1401 1402 bool tryMerge_TMacro() { 1403 if (Tokens.size() < 4) 1404 return false; 1405 FormatToken *Last = Tokens.back(); 1406 if (!Last->is(tok::r_paren)) 1407 return false; 1408 1409 FormatToken *String = Tokens[Tokens.size() - 2]; 1410 if (!String->is(tok::string_literal) || String->IsMultiline) 1411 return false; 1412 1413 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) 1414 return false; 1415 1416 FormatToken *Macro = Tokens[Tokens.size() - 4]; 1417 if (Macro->TokenText != "_T") 1418 return false; 1419 1420 const char *Start = Macro->TokenText.data(); 1421 const char *End = Last->TokenText.data() + Last->TokenText.size(); 1422 String->TokenText = StringRef(Start, End - Start); 1423 String->IsFirst = Macro->IsFirst; 1424 String->LastNewlineOffset = Macro->LastNewlineOffset; 1425 String->WhitespaceRange = Macro->WhitespaceRange; 1426 String->OriginalColumn = Macro->OriginalColumn; 1427 String->ColumnWidth = encoding::columnWidthWithTabs( 1428 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); 1429 1430 Tokens.pop_back(); 1431 Tokens.pop_back(); 1432 Tokens.pop_back(); 1433 Tokens.back() = String; 1434 return true; 1435 } 1436 1437 bool tryMergeConflictMarkers() { 1438 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof)) 1439 return false; 1440 1441 // Conflict lines look like: 1442 // <marker> <text from the vcs> 1443 // For example: 1444 // >>>>>>> /file/in/file/system at revision 1234 1445 // 1446 // We merge all tokens in a line that starts with a conflict marker 1447 // into a single token with a special token type that the unwrapped line 1448 // parser will use to correctly rebuild the underlying code. 1449 1450 FileID ID; 1451 // Get the position of the first token in the line. 1452 unsigned FirstInLineOffset; 1453 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc( 1454 Tokens[FirstInLineIndex]->getStartOfNonWhitespace()); 1455 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer(); 1456 // Calculate the offset of the start of the current line. 1457 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset); 1458 if (LineOffset == StringRef::npos) { 1459 LineOffset = 0; 1460 } else { 1461 ++LineOffset; 1462 } 1463 1464 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset); 1465 StringRef LineStart; 1466 if (FirstSpace == StringRef::npos) { 1467 LineStart = Buffer.substr(LineOffset); 1468 } else { 1469 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset); 1470 } 1471 1472 TokenType Type = TT_Unknown; 1473 if (LineStart == "<<<<<<<" || LineStart == ">>>>") { 1474 Type = TT_ConflictStart; 1475 } else if (LineStart == "|||||||" || LineStart == "=======" || 1476 LineStart == "====") { 1477 Type = TT_ConflictAlternative; 1478 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") { 1479 Type = TT_ConflictEnd; 1480 } 1481 1482 if (Type != TT_Unknown) { 1483 FormatToken *Next = Tokens.back(); 1484 1485 Tokens.resize(FirstInLineIndex + 1); 1486 // We do not need to build a complete token here, as we will skip it 1487 // during parsing anyway (as we must not touch whitespace around conflict 1488 // markers). 1489 Tokens.back()->Type = Type; 1490 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype); 1491 1492 Tokens.push_back(Next); 1493 return true; 1494 } 1495 1496 return false; 1497 } 1498 1499 FormatToken *getNextToken() { 1500 if (GreaterStashed) { 1501 // Create a synthesized second '>' token. 1502 // FIXME: Increment Column and set OriginalColumn. 1503 Token Greater = FormatTok->Tok; 1504 FormatTok = new (Allocator.Allocate()) FormatToken; 1505 FormatTok->Tok = Greater; 1506 SourceLocation GreaterLocation = 1507 FormatTok->Tok.getLocation().getLocWithOffset(1); 1508 FormatTok->WhitespaceRange = 1509 SourceRange(GreaterLocation, GreaterLocation); 1510 FormatTok->TokenText = ">"; 1511 FormatTok->ColumnWidth = 1; 1512 GreaterStashed = false; 1513 return FormatTok; 1514 } 1515 1516 FormatTok = new (Allocator.Allocate()) FormatToken; 1517 readRawToken(*FormatTok); 1518 SourceLocation WhitespaceStart = 1519 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); 1520 FormatTok->IsFirst = IsFirstToken; 1521 IsFirstToken = false; 1522 1523 // Consume and record whitespace until we find a significant token. 1524 unsigned WhitespaceLength = TrailingWhitespace; 1525 while (FormatTok->Tok.is(tok::unknown)) { 1526 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) { 1527 switch (FormatTok->TokenText[i]) { 1528 case '\n': 1529 ++FormatTok->NewlinesBefore; 1530 // FIXME: This is technically incorrect, as it could also 1531 // be a literal backslash at the end of the line. 1532 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' && 1533 (FormatTok->TokenText[i - 1] != '\r' || i == 1 || 1534 FormatTok->TokenText[i - 2] != '\\'))) 1535 FormatTok->HasUnescapedNewline = true; 1536 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 1537 Column = 0; 1538 break; 1539 case '\r': 1540 case '\f': 1541 case '\v': 1542 Column = 0; 1543 break; 1544 case ' ': 1545 ++Column; 1546 break; 1547 case '\t': 1548 Column += Style.TabWidth - Column % Style.TabWidth; 1549 break; 1550 case '\\': 1551 ++Column; 1552 if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' && 1553 FormatTok->TokenText[i + 1] != '\n')) 1554 FormatTok->Type = TT_ImplicitStringLiteral; 1555 break; 1556 default: 1557 FormatTok->Type = TT_ImplicitStringLiteral; 1558 ++Column; 1559 break; 1560 } 1561 } 1562 1563 if (FormatTok->Type == TT_ImplicitStringLiteral) 1564 break; 1565 WhitespaceLength += FormatTok->Tok.getLength(); 1566 1567 readRawToken(*FormatTok); 1568 } 1569 1570 // In case the token starts with escaped newlines, we want to 1571 // take them into account as whitespace - this pattern is quite frequent 1572 // in macro definitions. 1573 // FIXME: Add a more explicit test. 1574 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' && 1575 FormatTok->TokenText[1] == '\n') { 1576 ++FormatTok->NewlinesBefore; 1577 WhitespaceLength += 2; 1578 Column = 0; 1579 FormatTok->TokenText = FormatTok->TokenText.substr(2); 1580 } 1581 1582 FormatTok->WhitespaceRange = SourceRange( 1583 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); 1584 1585 FormatTok->OriginalColumn = Column; 1586 1587 TrailingWhitespace = 0; 1588 if (FormatTok->Tok.is(tok::comment)) { 1589 // FIXME: Add the trimmed whitespace to Column. 1590 StringRef UntrimmedText = FormatTok->TokenText; 1591 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); 1592 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); 1593 } else if (FormatTok->Tok.is(tok::raw_identifier)) { 1594 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); 1595 FormatTok->Tok.setIdentifierInfo(&Info); 1596 FormatTok->Tok.setKind(Info.getTokenID()); 1597 } else if (FormatTok->Tok.is(tok::greatergreater)) { 1598 FormatTok->Tok.setKind(tok::greater); 1599 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 1600 GreaterStashed = true; 1601 } 1602 1603 // Now FormatTok is the next non-whitespace token. 1604 1605 StringRef Text = FormatTok->TokenText; 1606 size_t FirstNewlinePos = Text.find('\n'); 1607 if (FirstNewlinePos == StringRef::npos) { 1608 // FIXME: ColumnWidth actually depends on the start column, we need to 1609 // take this into account when the token is moved. 1610 FormatTok->ColumnWidth = 1611 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); 1612 Column += FormatTok->ColumnWidth; 1613 } else { 1614 FormatTok->IsMultiline = true; 1615 // FIXME: ColumnWidth actually depends on the start column, we need to 1616 // take this into account when the token is moved. 1617 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 1618 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); 1619 1620 // The last line of the token always starts in column 0. 1621 // Thus, the length can be precomputed even in the presence of tabs. 1622 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( 1623 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, 1624 Encoding); 1625 Column = FormatTok->LastLineColumnWidth; 1626 } 1627 1628 FormatTok->IsForEachMacro = 1629 std::binary_search(ForEachMacros.begin(), ForEachMacros.end(), 1630 FormatTok->Tok.getIdentifierInfo()); 1631 1632 return FormatTok; 1633 } 1634 1635 FormatToken *FormatTok; 1636 bool IsFirstToken; 1637 bool GreaterStashed; 1638 unsigned Column; 1639 unsigned TrailingWhitespace; 1640 Lexer &Lex; 1641 SourceManager &SourceMgr; 1642 FormatStyle &Style; 1643 IdentifierTable IdentTable; 1644 encoding::Encoding Encoding; 1645 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator; 1646 // Index (in 'Tokens') of the last token that starts a new line. 1647 unsigned FirstInLineIndex; 1648 SmallVector<FormatToken *, 16> Tokens; 1649 SmallVector<IdentifierInfo *, 8> ForEachMacros; 1650 1651 bool FormattingDisabled; 1652 1653 void readRawToken(FormatToken &Tok) { 1654 Lex.LexFromRawLexer(Tok.Tok); 1655 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), 1656 Tok.Tok.getLength()); 1657 // For formatting, treat unterminated string literals like normal string 1658 // literals. 1659 if (Tok.is(tok::unknown)) { 1660 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') { 1661 Tok.Tok.setKind(tok::string_literal); 1662 Tok.IsUnterminatedLiteral = true; 1663 } else if (Style.Language == FormatStyle::LK_JavaScript && 1664 Tok.TokenText == "''") { 1665 Tok.Tok.setKind(tok::char_constant); 1666 } 1667 } 1668 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format on") 1669 FormattingDisabled = false; 1670 Tok.Finalized = FormattingDisabled; 1671 if (Tok.is(tok::comment) && Tok.TokenText == "// clang-format off") 1672 FormattingDisabled = true; 1673 } 1674 }; 1675 1676 static StringRef getLanguageName(FormatStyle::LanguageKind Language) { 1677 switch (Language) { 1678 case FormatStyle::LK_Cpp: 1679 return "C++"; 1680 case FormatStyle::LK_JavaScript: 1681 return "JavaScript"; 1682 case FormatStyle::LK_Proto: 1683 return "Proto"; 1684 default: 1685 return "Unknown"; 1686 } 1687 } 1688 1689 class Formatter : public UnwrappedLineConsumer { 1690 public: 1691 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr, 1692 const std::vector<CharSourceRange> &Ranges) 1693 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), 1694 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())), 1695 Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1), 1696 Encoding(encoding::detectEncoding(Lex.getBuffer())) { 1697 DEBUG(llvm::dbgs() << "File encoding: " 1698 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" 1699 : "unknown") 1700 << "\n"); 1701 DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language) 1702 << "\n"); 1703 } 1704 1705 tooling::Replacements format() { 1706 tooling::Replacements Result; 1707 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding); 1708 1709 UnwrappedLineParser Parser(Style, Tokens.lex(), *this); 1710 bool StructuralError = Parser.parse(); 1711 assert(UnwrappedLines.rbegin()->empty()); 1712 for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; 1713 ++Run) { 1714 DEBUG(llvm::dbgs() << "Run " << Run << "...\n"); 1715 SmallVector<AnnotatedLine *, 16> AnnotatedLines; 1716 for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) { 1717 AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i])); 1718 } 1719 tooling::Replacements RunResult = 1720 format(AnnotatedLines, StructuralError, Tokens); 1721 DEBUG({ 1722 llvm::dbgs() << "Replacements for run " << Run << ":\n"; 1723 for (tooling::Replacements::iterator I = RunResult.begin(), 1724 E = RunResult.end(); 1725 I != E; ++I) { 1726 llvm::dbgs() << I->toString() << "\n"; 1727 } 1728 }); 1729 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1730 delete AnnotatedLines[i]; 1731 } 1732 Result.insert(RunResult.begin(), RunResult.end()); 1733 Whitespaces.reset(); 1734 } 1735 return Result; 1736 } 1737 1738 tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, 1739 bool StructuralError, FormatTokenLexer &Tokens) { 1740 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in")); 1741 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1742 Annotator.annotate(*AnnotatedLines[i]); 1743 } 1744 deriveLocalStyle(AnnotatedLines); 1745 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1746 Annotator.calculateFormattingInformation(*AnnotatedLines[i]); 1747 } 1748 computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end()); 1749 1750 Annotator.setCommentLineLevels(AnnotatedLines); 1751 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding, 1752 BinPackInconclusiveFunctions); 1753 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style); 1754 Formatter.format(AnnotatedLines, /*DryRun=*/false); 1755 return Whitespaces.generateReplacements(); 1756 } 1757 1758 private: 1759 // Determines which lines are affected by the SourceRanges given as input. 1760 // Returns \c true if at least one line between I and E or one of their 1761 // children is affected. 1762 bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I, 1763 SmallVectorImpl<AnnotatedLine *>::iterator E) { 1764 bool SomeLineAffected = false; 1765 const AnnotatedLine *PreviousLine = nullptr; 1766 while (I != E) { 1767 AnnotatedLine *Line = *I; 1768 Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First); 1769 1770 // If a line is part of a preprocessor directive, it needs to be formatted 1771 // if any token within the directive is affected. 1772 if (Line->InPPDirective) { 1773 FormatToken *Last = Line->Last; 1774 SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1; 1775 while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) { 1776 Last = (*PPEnd)->Last; 1777 ++PPEnd; 1778 } 1779 1780 if (affectsTokenRange(*Line->First, *Last, 1781 /*IncludeLeadingNewlines=*/false)) { 1782 SomeLineAffected = true; 1783 markAllAsAffected(I, PPEnd); 1784 } 1785 I = PPEnd; 1786 continue; 1787 } 1788 1789 if (nonPPLineAffected(Line, PreviousLine)) 1790 SomeLineAffected = true; 1791 1792 PreviousLine = Line; 1793 ++I; 1794 } 1795 return SomeLineAffected; 1796 } 1797 1798 // Determines whether 'Line' is affected by the SourceRanges given as input. 1799 // Returns \c true if line or one if its children is affected. 1800 bool nonPPLineAffected(AnnotatedLine *Line, 1801 const AnnotatedLine *PreviousLine) { 1802 bool SomeLineAffected = false; 1803 Line->ChildrenAffected = 1804 computeAffectedLines(Line->Children.begin(), Line->Children.end()); 1805 if (Line->ChildrenAffected) 1806 SomeLineAffected = true; 1807 1808 // Stores whether one of the line's tokens is directly affected. 1809 bool SomeTokenAffected = false; 1810 // Stores whether we need to look at the leading newlines of the next token 1811 // in order to determine whether it was affected. 1812 bool IncludeLeadingNewlines = false; 1813 1814 // Stores whether the first child line of any of this line's tokens is 1815 // affected. 1816 bool SomeFirstChildAffected = false; 1817 1818 for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 1819 // Determine whether 'Tok' was affected. 1820 if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines)) 1821 SomeTokenAffected = true; 1822 1823 // Determine whether the first child of 'Tok' was affected. 1824 if (!Tok->Children.empty() && Tok->Children.front()->Affected) 1825 SomeFirstChildAffected = true; 1826 1827 IncludeLeadingNewlines = Tok->Children.empty(); 1828 } 1829 1830 // Was this line moved, i.e. has it previously been on the same line as an 1831 // affected line? 1832 bool LineMoved = PreviousLine && PreviousLine->Affected && 1833 Line->First->NewlinesBefore == 0; 1834 1835 bool IsContinuedComment = 1836 Line->First->is(tok::comment) && Line->First->Next == nullptr && 1837 Line->First->NewlinesBefore < 2 && PreviousLine && 1838 PreviousLine->Affected && PreviousLine->Last->is(tok::comment); 1839 1840 if (SomeTokenAffected || SomeFirstChildAffected || LineMoved || 1841 IsContinuedComment) { 1842 Line->Affected = true; 1843 SomeLineAffected = true; 1844 } 1845 return SomeLineAffected; 1846 } 1847 1848 // Marks all lines between I and E as well as all their children as affected. 1849 void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I, 1850 SmallVectorImpl<AnnotatedLine *>::iterator E) { 1851 while (I != E) { 1852 (*I)->Affected = true; 1853 markAllAsAffected((*I)->Children.begin(), (*I)->Children.end()); 1854 ++I; 1855 } 1856 } 1857 1858 // Returns true if the range from 'First' to 'Last' intersects with one of the 1859 // input ranges. 1860 bool affectsTokenRange(const FormatToken &First, const FormatToken &Last, 1861 bool IncludeLeadingNewlines) { 1862 SourceLocation Start = First.WhitespaceRange.getBegin(); 1863 if (!IncludeLeadingNewlines) 1864 Start = Start.getLocWithOffset(First.LastNewlineOffset); 1865 SourceLocation End = Last.getStartOfNonWhitespace(); 1866 if (Last.TokenText.size() > 0) 1867 End = End.getLocWithOffset(Last.TokenText.size() - 1); 1868 CharSourceRange Range = CharSourceRange::getCharRange(Start, End); 1869 return affectsCharSourceRange(Range); 1870 } 1871 1872 // Returns true if one of the input ranges intersect the leading empty lines 1873 // before 'Tok'. 1874 bool affectsLeadingEmptyLines(const FormatToken &Tok) { 1875 CharSourceRange EmptyLineRange = CharSourceRange::getCharRange( 1876 Tok.WhitespaceRange.getBegin(), 1877 Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset)); 1878 return affectsCharSourceRange(EmptyLineRange); 1879 } 1880 1881 // Returns true if 'Range' intersects with one of the input ranges. 1882 bool affectsCharSourceRange(const CharSourceRange &Range) { 1883 for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(), 1884 E = Ranges.end(); 1885 I != E; ++I) { 1886 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) && 1887 !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin())) 1888 return true; 1889 } 1890 return false; 1891 } 1892 1893 static bool inputUsesCRLF(StringRef Text) { 1894 return Text.count('\r') * 2 > Text.count('\n'); 1895 } 1896 1897 void 1898 deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 1899 unsigned CountBoundToVariable = 0; 1900 unsigned CountBoundToType = 0; 1901 bool HasCpp03IncompatibleFormat = false; 1902 bool HasBinPackedFunction = false; 1903 bool HasOnePerLineFunction = false; 1904 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1905 if (!AnnotatedLines[i]->First->Next) 1906 continue; 1907 FormatToken *Tok = AnnotatedLines[i]->First->Next; 1908 while (Tok->Next) { 1909 if (Tok->Type == TT_PointerOrReference) { 1910 bool SpacesBefore = 1911 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd(); 1912 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() != 1913 Tok->Next->WhitespaceRange.getEnd(); 1914 if (SpacesBefore && !SpacesAfter) 1915 ++CountBoundToVariable; 1916 else if (!SpacesBefore && SpacesAfter) 1917 ++CountBoundToType; 1918 } 1919 1920 if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) { 1921 if (Tok->is(tok::coloncolon) && 1922 Tok->Previous->Type == TT_TemplateOpener) 1923 HasCpp03IncompatibleFormat = true; 1924 if (Tok->Type == TT_TemplateCloser && 1925 Tok->Previous->Type == TT_TemplateCloser) 1926 HasCpp03IncompatibleFormat = true; 1927 } 1928 1929 if (Tok->PackingKind == PPK_BinPacked) 1930 HasBinPackedFunction = true; 1931 if (Tok->PackingKind == PPK_OnePerLine) 1932 HasOnePerLineFunction = true; 1933 1934 Tok = Tok->Next; 1935 } 1936 } 1937 if (Style.DerivePointerAlignment) { 1938 if (CountBoundToType > CountBoundToVariable) 1939 Style.PointerAlignment = FormatStyle::PAS_Left; 1940 else if (CountBoundToType < CountBoundToVariable) 1941 Style.PointerAlignment = FormatStyle::PAS_Right; 1942 } 1943 if (Style.Standard == FormatStyle::LS_Auto) { 1944 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11 1945 : FormatStyle::LS_Cpp03; 1946 } 1947 BinPackInconclusiveFunctions = 1948 HasBinPackedFunction || !HasOnePerLineFunction; 1949 } 1950 1951 void consumeUnwrappedLine(const UnwrappedLine &TheLine) override { 1952 assert(!UnwrappedLines.empty()); 1953 UnwrappedLines.back().push_back(TheLine); 1954 } 1955 1956 void finishRun() override { 1957 UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>()); 1958 } 1959 1960 FormatStyle Style; 1961 Lexer &Lex; 1962 SourceManager &SourceMgr; 1963 WhitespaceManager Whitespaces; 1964 SmallVector<CharSourceRange, 8> Ranges; 1965 SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines; 1966 1967 encoding::Encoding Encoding; 1968 bool BinPackInconclusiveFunctions; 1969 }; 1970 1971 } // end anonymous namespace 1972 1973 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex, 1974 SourceManager &SourceMgr, 1975 std::vector<CharSourceRange> Ranges) { 1976 if (Style.DisableFormat) { 1977 tooling::Replacements EmptyResult; 1978 return EmptyResult; 1979 } 1980 1981 Formatter formatter(Style, Lex, SourceMgr, Ranges); 1982 return formatter.format(); 1983 } 1984 1985 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 1986 std::vector<tooling::Range> Ranges, 1987 StringRef FileName) { 1988 FileManager Files((FileSystemOptions())); 1989 DiagnosticsEngine Diagnostics( 1990 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), 1991 new DiagnosticOptions); 1992 SourceManager SourceMgr(Diagnostics, Files); 1993 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName); 1994 const clang::FileEntry *Entry = 1995 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0); 1996 SourceMgr.overrideFileContents(Entry, Buf); 1997 FileID ID = 1998 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User); 1999 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, 2000 getFormattingLangOpts(Style.Standard)); 2001 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID); 2002 std::vector<CharSourceRange> CharRanges; 2003 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { 2004 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset()); 2005 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength()); 2006 CharRanges.push_back(CharSourceRange::getCharRange(Start, End)); 2007 } 2008 return reformat(Style, Lex, SourceMgr, CharRanges); 2009 } 2010 2011 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) { 2012 LangOptions LangOpts; 2013 LangOpts.CPlusPlus = 1; 2014 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2015 LangOpts.CPlusPlus14 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 2016 LangOpts.LineComment = 1; 2017 LangOpts.CXXOperatorNames = 1; 2018 LangOpts.Bool = 1; 2019 LangOpts.ObjC1 = 1; 2020 LangOpts.ObjC2 = 1; 2021 return LangOpts; 2022 } 2023 2024 const char *StyleOptionHelpDescription = 2025 "Coding style, currently supports:\n" 2026 " LLVM, Google, Chromium, Mozilla, WebKit.\n" 2027 "Use -style=file to load style configuration from\n" 2028 ".clang-format file located in one of the parent\n" 2029 "directories of the source file (or current\n" 2030 "directory for stdin).\n" 2031 "Use -style=\"{key: value, ...}\" to set specific\n" 2032 "parameters, e.g.:\n" 2033 " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; 2034 2035 static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) { 2036 if (FileName.endswith_lower(".js")) { 2037 return FormatStyle::LK_JavaScript; 2038 } else if (FileName.endswith_lower(".proto") || 2039 FileName.endswith_lower(".protodevel")) { 2040 return FormatStyle::LK_Proto; 2041 } 2042 return FormatStyle::LK_Cpp; 2043 } 2044 2045 FormatStyle getStyle(StringRef StyleName, StringRef FileName, 2046 StringRef FallbackStyle) { 2047 FormatStyle Style = getLLVMStyle(); 2048 Style.Language = getLanguageByFileName(FileName); 2049 if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) { 2050 llvm::errs() << "Invalid fallback style \"" << FallbackStyle 2051 << "\" using LLVM style\n"; 2052 return Style; 2053 } 2054 2055 if (StyleName.startswith("{")) { 2056 // Parse YAML/JSON style from the command line. 2057 if (std::error_code ec = parseConfiguration(StyleName, &Style)) { 2058 llvm::errs() << "Error parsing -style: " << ec.message() << ", using " 2059 << FallbackStyle << " style\n"; 2060 } 2061 return Style; 2062 } 2063 2064 if (!StyleName.equals_lower("file")) { 2065 if (!getPredefinedStyle(StyleName, Style.Language, &Style)) 2066 llvm::errs() << "Invalid value for -style, using " << FallbackStyle 2067 << " style\n"; 2068 return Style; 2069 } 2070 2071 // Look for .clang-format/_clang-format file in the file's parent directories. 2072 SmallString<128> UnsuitableConfigFiles; 2073 SmallString<128> Path(FileName); 2074 llvm::sys::fs::make_absolute(Path); 2075 for (StringRef Directory = Path; !Directory.empty(); 2076 Directory = llvm::sys::path::parent_path(Directory)) { 2077 if (!llvm::sys::fs::is_directory(Directory)) 2078 continue; 2079 SmallString<128> ConfigFile(Directory); 2080 2081 llvm::sys::path::append(ConfigFile, ".clang-format"); 2082 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); 2083 bool IsFile = false; 2084 // Ignore errors from is_regular_file: we only need to know if we can read 2085 // the file or not. 2086 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile); 2087 2088 if (!IsFile) { 2089 // Try _clang-format too, since dotfiles are not commonly used on Windows. 2090 ConfigFile = Directory; 2091 llvm::sys::path::append(ConfigFile, "_clang-format"); 2092 DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); 2093 llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile); 2094 } 2095 2096 if (IsFile) { 2097 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text = 2098 llvm::MemoryBuffer::getFile(ConfigFile.c_str()); 2099 if (std::error_code EC = Text.getError()) { 2100 llvm::errs() << EC.message() << "\n"; 2101 break; 2102 } 2103 if (std::error_code ec = 2104 parseConfiguration(Text.get()->getBuffer(), &Style)) { 2105 if (ec == ParseError::Unsuitable) { 2106 if (!UnsuitableConfigFiles.empty()) 2107 UnsuitableConfigFiles.append(", "); 2108 UnsuitableConfigFiles.append(ConfigFile); 2109 continue; 2110 } 2111 llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message() 2112 << "\n"; 2113 break; 2114 } 2115 DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); 2116 return Style; 2117 } 2118 } 2119 llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle 2120 << " style\n"; 2121 if (!UnsuitableConfigFiles.empty()) { 2122 llvm::errs() << "Configuration file(s) do(es) not support " 2123 << getLanguageName(Style.Language) << ": " 2124 << UnsuitableConfigFiles << "\n"; 2125 } 2126 return Style; 2127 } 2128 2129 } // namespace format 2130 } // namespace clang 2131