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