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