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