Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 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 | /// |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 16 | #define DEBUG_TYPE "format-formatter" |
| 17 | |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 18 | #include "ContinuationIndenter.h" |
Daniel Jasper | 32d28ee | 2013-01-29 21:01:14 +0000 | [diff] [blame] | 19 | #include "TokenAnnotator.h" |
Chandler Carruth | 55fc873 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 20 | #include "UnwrappedLineParser.h" |
Alexander Kornienko | 70ce788 | 2013-04-15 14:28:00 +0000 | [diff] [blame] | 21 | #include "WhitespaceManager.h" |
Daniel Jasper | 8a99945 | 2013-05-16 10:40:07 +0000 | [diff] [blame] | 22 | #include "clang/Basic/Diagnostic.h" |
Chandler Carruth | b99083e | 2013-01-02 10:28:36 +0000 | [diff] [blame] | 23 | #include "clang/Basic/SourceManager.h" |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 24 | #include "clang/Format/Format.h" |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 25 | #include "clang/Lex/Lexer.h" |
Alexander Kornienko | 5262dd9 | 2013-03-27 11:52:18 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/STLExtras.h" |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 27 | #include "llvm/Support/Allocator.h" |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 28 | #include "llvm/Support/Debug.h" |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 29 | #include "llvm/Support/YAMLTraits.h" |
Edwin Vane | f4e12c8 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 30 | #include "llvm/Support/Path.h" |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 31 | #include <queue> |
Daniel Jasper | 8822d3a | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 32 | #include <string> |
| 33 | |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 34 | namespace llvm { |
| 35 | namespace yaml { |
| 36 | template <> |
| 37 | struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> { |
Manuel Klimek | 44135b8 | 2013-05-13 12:51:40 +0000 | [diff] [blame] | 38 | static void enumeration(IO &IO, |
| 39 | clang::format::FormatStyle::LanguageStandard &Value) { |
Alexander Kornienko | 9321e87 | 2013-09-04 14:09:13 +0000 | [diff] [blame] | 40 | IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03); |
Manuel Klimek | 44135b8 | 2013-05-13 12:51:40 +0000 | [diff] [blame] | 41 | IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03); |
Alexander Kornienko | 9321e87 | 2013-09-04 14:09:13 +0000 | [diff] [blame] | 42 | IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11); |
Manuel Klimek | 44135b8 | 2013-05-13 12:51:40 +0000 | [diff] [blame] | 43 | IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11); |
| 44 | IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto); |
| 45 | } |
| 46 | }; |
| 47 | |
Daniel Jasper | 1fb8d88 | 2013-05-14 09:30:02 +0000 | [diff] [blame] | 48 | template <> |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 49 | struct ScalarEnumerationTraits<clang::format::FormatStyle::UseTabStyle> { |
Alexander Kornienko | f0fc89c | 2013-10-14 00:46:35 +0000 | [diff] [blame] | 50 | static void enumeration(IO &IO, |
| 51 | clang::format::FormatStyle::UseTabStyle &Value) { |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 52 | IO.enumCase(Value, "Never", clang::format::FormatStyle::UT_Never); |
| 53 | IO.enumCase(Value, "false", clang::format::FormatStyle::UT_Never); |
| 54 | IO.enumCase(Value, "Always", clang::format::FormatStyle::UT_Always); |
| 55 | IO.enumCase(Value, "true", clang::format::FormatStyle::UT_Always); |
| 56 | IO.enumCase(Value, "ForIndentation", |
| 57 | clang::format::FormatStyle::UT_ForIndentation); |
| 58 | } |
| 59 | }; |
| 60 | |
| 61 | template <> |
Manuel Klimek | 44135b8 | 2013-05-13 12:51:40 +0000 | [diff] [blame] | 62 | struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> { |
| 63 | static void |
| 64 | enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) { |
| 65 | IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach); |
| 66 | IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux); |
| 67 | IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup); |
Manuel Klimek | e490705 | 2013-08-02 21:31:59 +0000 | [diff] [blame] | 68 | IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 69 | } |
| 70 | }; |
| 71 | |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 72 | template <> |
| 73 | struct ScalarEnumerationTraits< |
| 74 | clang::format::FormatStyle::NamespaceIndentationKind> { |
| 75 | static void |
| 76 | enumeration(IO &IO, |
| 77 | clang::format::FormatStyle::NamespaceIndentationKind &Value) { |
| 78 | IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None); |
| 79 | IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner); |
| 80 | IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All); |
| 81 | } |
| 82 | }; |
| 83 | |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 84 | template <> struct MappingTraits<clang::format::FormatStyle> { |
| 85 | static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) { |
Alexander Kornienko | dd25631 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 86 | if (IO.outputting()) { |
Alexander Kornienko | 4e65c98 | 2013-09-02 16:39:23 +0000 | [diff] [blame] | 87 | StringRef StylesArray[] = { "LLVM", "Google", "Chromium", |
| 88 | "Mozilla", "WebKit" }; |
Alexander Kornienko | dd25631 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 89 | ArrayRef<StringRef> Styles(StylesArray); |
| 90 | for (size_t i = 0, e = Styles.size(); i < e; ++i) { |
| 91 | StringRef StyleName(Styles[i]); |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 92 | clang::format::FormatStyle PredefinedStyle; |
| 93 | if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) && |
| 94 | Style == PredefinedStyle) { |
Alexander Kornienko | dd25631 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 95 | IO.mapOptional("# BasedOnStyle", StyleName); |
| 96 | break; |
| 97 | } |
| 98 | } |
| 99 | } else { |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 100 | StringRef BasedOnStyle; |
| 101 | IO.mapOptional("BasedOnStyle", BasedOnStyle); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 102 | if (!BasedOnStyle.empty()) |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 103 | if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) { |
| 104 | IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle)); |
| 105 | return; |
| 106 | } |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 107 | } |
| 108 | |
| 109 | IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); |
Daniel Jasper | 6315fec | 2013-08-13 10:58:30 +0000 | [diff] [blame] | 110 | IO.mapOptional("ConstructorInitializerIndentWidth", |
| 111 | Style.ConstructorInitializerIndentWidth); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 112 | IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft); |
Daniel Jasper | 893ea8d | 2013-07-31 23:55:15 +0000 | [diff] [blame] | 113 | IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 114 | IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", |
| 115 | Style.AllowAllParametersOfDeclarationOnNextLine); |
| 116 | IO.mapOptional("AllowShortIfStatementsOnASingleLine", |
| 117 | Style.AllowShortIfStatementsOnASingleLine); |
Daniel Jasper | f11bbb9 | 2013-05-16 12:12:21 +0000 | [diff] [blame] | 118 | IO.mapOptional("AllowShortLoopsOnASingleLine", |
| 119 | Style.AllowShortLoopsOnASingleLine); |
Daniel Jasper | bbc8776 | 2013-05-29 12:07:31 +0000 | [diff] [blame] | 120 | IO.mapOptional("AlwaysBreakTemplateDeclarations", |
| 121 | Style.AlwaysBreakTemplateDeclarations); |
Alexander Kornienko | 5631202 | 2013-07-04 12:02:44 +0000 | [diff] [blame] | 122 | IO.mapOptional("AlwaysBreakBeforeMultilineStrings", |
| 123 | Style.AlwaysBreakBeforeMultilineStrings); |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 124 | IO.mapOptional("BreakBeforeBinaryOperators", |
| 125 | Style.BreakBeforeBinaryOperators); |
| 126 | IO.mapOptional("BreakConstructorInitializersBeforeComma", |
| 127 | Style.BreakConstructorInitializersBeforeComma); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 128 | IO.mapOptional("BinPackParameters", Style.BinPackParameters); |
| 129 | IO.mapOptional("ColumnLimit", Style.ColumnLimit); |
| 130 | IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", |
| 131 | Style.ConstructorInitializerAllOnOneLineOrOnePerLine); |
| 132 | IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding); |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 133 | IO.mapOptional("ExperimentalAutoDetectBinPacking", |
| 134 | Style.ExperimentalAutoDetectBinPacking); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 135 | IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); |
| 136 | IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 137 | IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 138 | IO.mapOptional("ObjCSpaceBeforeProtocolList", |
| 139 | Style.ObjCSpaceBeforeProtocolList); |
Daniel Jasper | 47066e4 | 2013-10-25 14:29:37 +0000 | [diff] [blame] | 140 | IO.mapOptional("PenaltyBreakBeforeFirstCallParameter", |
| 141 | Style.PenaltyBreakBeforeFirstCallParameter); |
Alexander Kornienko | 2785b9a | 2013-06-07 16:02:52 +0000 | [diff] [blame] | 142 | IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment); |
| 143 | IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString); |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 144 | IO.mapOptional("PenaltyBreakFirstLessLess", |
| 145 | Style.PenaltyBreakFirstLessLess); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 146 | IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); |
| 147 | IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", |
| 148 | Style.PenaltyReturnTypeOnItsOwnLine); |
| 149 | IO.mapOptional("PointerBindsToType", Style.PointerBindsToType); |
| 150 | IO.mapOptional("SpacesBeforeTrailingComments", |
| 151 | Style.SpacesBeforeTrailingComments); |
Daniel Jasper | b5dc3f4 | 2013-07-16 18:22:10 +0000 | [diff] [blame] | 152 | IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 153 | IO.mapOptional("Standard", Style.Standard); |
Manuel Klimek | 07a64ec | 2013-05-13 08:42:42 +0000 | [diff] [blame] | 154 | IO.mapOptional("IndentWidth", Style.IndentWidth); |
Alexander Kornienko | 0b62cc3 | 2013-09-05 14:08:34 +0000 | [diff] [blame] | 155 | IO.mapOptional("TabWidth", Style.TabWidth); |
Manuel Klimek | 7c9a93e | 2013-05-13 09:22:11 +0000 | [diff] [blame] | 156 | IO.mapOptional("UseTab", Style.UseTab); |
Manuel Klimek | 44135b8 | 2013-05-13 12:51:40 +0000 | [diff] [blame] | 157 | IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces); |
Manuel Klimek | a9a7f10 | 2013-06-21 17:25:42 +0000 | [diff] [blame] | 158 | IO.mapOptional("IndentFunctionDeclarationAfterType", |
| 159 | Style.IndentFunctionDeclarationAfterType); |
Daniel Jasper | 7df56bf | 2013-08-20 12:36:34 +0000 | [diff] [blame] | 160 | IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses); |
Daniel Jasper | d8ee5c1 | 2013-10-29 14:52:02 +0000 | [diff] [blame] | 161 | IO.mapOptional("SpacesInAngles", Style.SpacesInAngles); |
Daniel Jasper | 34f3d05 | 2013-08-21 08:39:01 +0000 | [diff] [blame] | 162 | IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses); |
Daniel Jasper | 7df56bf | 2013-08-20 12:36:34 +0000 | [diff] [blame] | 163 | IO.mapOptional("SpacesInCStyleCastParentheses", |
| 164 | Style.SpacesInCStyleCastParentheses); |
| 165 | IO.mapOptional("SpaceAfterControlStatementKeyword", |
| 166 | Style.SpaceAfterControlStatementKeyword); |
Daniel Jasper | 9b4de85 | 2013-09-25 15:15:02 +0000 | [diff] [blame] | 167 | IO.mapOptional("SpaceBeforeAssignmentOperators", |
| 168 | Style.SpaceBeforeAssignmentOperators); |
Daniel Jasper | c2827ec | 2013-10-18 10:38:14 +0000 | [diff] [blame] | 169 | IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 170 | } |
| 171 | }; |
| 172 | } |
| 173 | } |
| 174 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 175 | namespace clang { |
| 176 | namespace format { |
| 177 | |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 178 | void setDefaultPenalties(FormatStyle &Style) { |
Daniel Jasper | f546178 | 2013-08-28 10:03:58 +0000 | [diff] [blame] | 179 | Style.PenaltyBreakComment = 60; |
Daniel Jasper | 9637dda | 2013-07-15 14:33:14 +0000 | [diff] [blame] | 180 | Style.PenaltyBreakFirstLessLess = 120; |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 181 | Style.PenaltyBreakString = 1000; |
| 182 | Style.PenaltyExcessCharacter = 1000000; |
| 183 | } |
| 184 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 185 | FormatStyle getLLVMStyle() { |
| 186 | FormatStyle LLVMStyle; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 187 | LLVMStyle.AccessModifierOffset = -2; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 188 | LLVMStyle.AlignEscapedNewlinesLeft = false; |
Daniel Jasper | 893ea8d | 2013-07-31 23:55:15 +0000 | [diff] [blame] | 189 | LLVMStyle.AlignTrailingComments = true; |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 190 | LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 191 | LLVMStyle.AllowShortIfStatementsOnASingleLine = false; |
Daniel Jasper | f11bbb9 | 2013-05-16 12:12:21 +0000 | [diff] [blame] | 192 | LLVMStyle.AllowShortLoopsOnASingleLine = false; |
Alexander Kornienko | 5631202 | 2013-07-04 12:02:44 +0000 | [diff] [blame] | 193 | LLVMStyle.AlwaysBreakBeforeMultilineStrings = false; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 194 | LLVMStyle.AlwaysBreakTemplateDeclarations = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 195 | LLVMStyle.BinPackParameters = true; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 196 | LLVMStyle.BreakBeforeBinaryOperators = false; |
| 197 | LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; |
| 198 | LLVMStyle.BreakConstructorInitializersBeforeComma = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 199 | LLVMStyle.ColumnLimit = 80; |
| 200 | LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; |
Daniel Jasper | 6315fec | 2013-08-13 10:58:30 +0000 | [diff] [blame] | 201 | LLVMStyle.ConstructorInitializerIndentWidth = 4; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 202 | LLVMStyle.Cpp11BracedListStyle = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 203 | LLVMStyle.DerivePointerBinding = false; |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 204 | LLVMStyle.ExperimentalAutoDetectBinPacking = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 205 | LLVMStyle.IndentCaseLabels = false; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 206 | LLVMStyle.IndentFunctionDeclarationAfterType = false; |
| 207 | LLVMStyle.IndentWidth = 2; |
Alexander Kornienko | 0b62cc3 | 2013-09-05 14:08:34 +0000 | [diff] [blame] | 208 | LLVMStyle.TabWidth = 8; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 209 | LLVMStyle.MaxEmptyLinesToKeep = 1; |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 210 | LLVMStyle.NamespaceIndentation = FormatStyle::NI_None; |
Nico Weber | 5f500df | 2013-01-10 20:12:55 +0000 | [diff] [blame] | 211 | LLVMStyle.ObjCSpaceBeforeProtocolList = true; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 212 | LLVMStyle.PointerBindsToType = false; |
| 213 | LLVMStyle.SpacesBeforeTrailingComments = 1; |
| 214 | LLVMStyle.Standard = FormatStyle::LS_Cpp03; |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 215 | LLVMStyle.UseTab = FormatStyle::UT_Never; |
Daniel Jasper | 7df56bf | 2013-08-20 12:36:34 +0000 | [diff] [blame] | 216 | LLVMStyle.SpacesInParentheses = false; |
| 217 | LLVMStyle.SpaceInEmptyParentheses = false; |
| 218 | LLVMStyle.SpacesInCStyleCastParentheses = false; |
| 219 | LLVMStyle.SpaceAfterControlStatementKeyword = true; |
Daniel Jasper | 9b4de85 | 2013-09-25 15:15:02 +0000 | [diff] [blame] | 220 | LLVMStyle.SpaceBeforeAssignmentOperators = true; |
Daniel Jasper | c2827ec | 2013-10-18 10:38:14 +0000 | [diff] [blame] | 221 | LLVMStyle.ContinuationIndentWidth = 4; |
Daniel Jasper | d8ee5c1 | 2013-10-29 14:52:02 +0000 | [diff] [blame] | 222 | LLVMStyle.SpacesInAngles = false; |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 223 | |
| 224 | setDefaultPenalties(LLVMStyle); |
| 225 | LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60; |
Daniel Jasper | 47066e4 | 2013-10-25 14:29:37 +0000 | [diff] [blame] | 226 | LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19; |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 227 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 228 | return LLVMStyle; |
| 229 | } |
| 230 | |
| 231 | FormatStyle getGoogleStyle() { |
| 232 | FormatStyle GoogleStyle; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 233 | GoogleStyle.AccessModifierOffset = -1; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 234 | GoogleStyle.AlignEscapedNewlinesLeft = true; |
Daniel Jasper | 893ea8d | 2013-07-31 23:55:15 +0000 | [diff] [blame] | 235 | GoogleStyle.AlignTrailingComments = true; |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 236 | GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true; |
Daniel Jasper | 94d6ad7 | 2013-04-24 13:46:00 +0000 | [diff] [blame] | 237 | GoogleStyle.AllowShortIfStatementsOnASingleLine = true; |
Daniel Jasper | 1bee073 | 2013-05-23 18:05:18 +0000 | [diff] [blame] | 238 | GoogleStyle.AllowShortLoopsOnASingleLine = true; |
Alexander Kornienko | 5631202 | 2013-07-04 12:02:44 +0000 | [diff] [blame] | 239 | GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 240 | GoogleStyle.AlwaysBreakTemplateDeclarations = true; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 241 | GoogleStyle.BinPackParameters = true; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 242 | GoogleStyle.BreakBeforeBinaryOperators = false; |
| 243 | GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach; |
| 244 | GoogleStyle.BreakConstructorInitializersBeforeComma = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 245 | GoogleStyle.ColumnLimit = 80; |
| 246 | GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; |
Daniel Jasper | 6315fec | 2013-08-13 10:58:30 +0000 | [diff] [blame] | 247 | GoogleStyle.ConstructorInitializerIndentWidth = 4; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 248 | GoogleStyle.Cpp11BracedListStyle = true; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 249 | GoogleStyle.DerivePointerBinding = true; |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 250 | GoogleStyle.ExperimentalAutoDetectBinPacking = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 251 | GoogleStyle.IndentCaseLabels = true; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 252 | GoogleStyle.IndentFunctionDeclarationAfterType = true; |
| 253 | GoogleStyle.IndentWidth = 2; |
Alexander Kornienko | 0b62cc3 | 2013-09-05 14:08:34 +0000 | [diff] [blame] | 254 | GoogleStyle.TabWidth = 8; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 255 | GoogleStyle.MaxEmptyLinesToKeep = 1; |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 256 | GoogleStyle.NamespaceIndentation = FormatStyle::NI_None; |
Nico Weber | 5f500df | 2013-01-10 20:12:55 +0000 | [diff] [blame] | 257 | GoogleStyle.ObjCSpaceBeforeProtocolList = false; |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 258 | GoogleStyle.PointerBindsToType = true; |
| 259 | GoogleStyle.SpacesBeforeTrailingComments = 2; |
| 260 | GoogleStyle.Standard = FormatStyle::LS_Auto; |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 261 | GoogleStyle.UseTab = FormatStyle::UT_Never; |
Daniel Jasper | 7df56bf | 2013-08-20 12:36:34 +0000 | [diff] [blame] | 262 | GoogleStyle.SpacesInParentheses = false; |
| 263 | GoogleStyle.SpaceInEmptyParentheses = false; |
| 264 | GoogleStyle.SpacesInCStyleCastParentheses = false; |
| 265 | GoogleStyle.SpaceAfterControlStatementKeyword = true; |
Daniel Jasper | 9b4de85 | 2013-09-25 15:15:02 +0000 | [diff] [blame] | 266 | GoogleStyle.SpaceBeforeAssignmentOperators = true; |
Daniel Jasper | c2827ec | 2013-10-18 10:38:14 +0000 | [diff] [blame] | 267 | GoogleStyle.ContinuationIndentWidth = 4; |
Daniel Jasper | d8ee5c1 | 2013-10-29 14:52:02 +0000 | [diff] [blame] | 268 | GoogleStyle.SpacesInAngles = false; |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 269 | |
| 270 | setDefaultPenalties(GoogleStyle); |
| 271 | GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; |
Daniel Jasper | 47066e4 | 2013-10-25 14:29:37 +0000 | [diff] [blame] | 272 | GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1; |
Daniel Jasper | faec47b | 2013-07-11 20:41:21 +0000 | [diff] [blame] | 273 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 274 | return GoogleStyle; |
| 275 | } |
| 276 | |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 277 | FormatStyle getChromiumStyle() { |
| 278 | FormatStyle ChromiumStyle = getGoogleStyle(); |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 279 | ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; |
Daniel Jasper | 94d6ad7 | 2013-04-24 13:46:00 +0000 | [diff] [blame] | 280 | ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; |
Daniel Jasper | f11bbb9 | 2013-05-16 12:12:21 +0000 | [diff] [blame] | 281 | ChromiumStyle.AllowShortLoopsOnASingleLine = false; |
Daniel Jasper | faab0d3 | 2013-02-27 09:47:53 +0000 | [diff] [blame] | 282 | ChromiumStyle.BinPackParameters = false; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 283 | ChromiumStyle.DerivePointerBinding = false; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 284 | ChromiumStyle.Standard = FormatStyle::LS_Cpp03; |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 285 | return ChromiumStyle; |
| 286 | } |
| 287 | |
Alexander Kornienko | fb59486 | 2013-05-06 14:11:27 +0000 | [diff] [blame] | 288 | FormatStyle getMozillaStyle() { |
| 289 | FormatStyle MozillaStyle = getLLVMStyle(); |
| 290 | MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; |
| 291 | MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; |
| 292 | MozillaStyle.DerivePointerBinding = true; |
| 293 | MozillaStyle.IndentCaseLabels = true; |
| 294 | MozillaStyle.ObjCSpaceBeforeProtocolList = false; |
| 295 | MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; |
| 296 | MozillaStyle.PointerBindsToType = true; |
| 297 | return MozillaStyle; |
| 298 | } |
| 299 | |
Daniel Jasper | e05dc6d | 2013-07-24 13:10:59 +0000 | [diff] [blame] | 300 | FormatStyle getWebKitStyle() { |
| 301 | FormatStyle Style = getLLVMStyle(); |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 302 | Style.AccessModifierOffset = -4; |
Daniel Jasper | 893ea8d | 2013-07-31 23:55:15 +0000 | [diff] [blame] | 303 | Style.AlignTrailingComments = false; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 304 | Style.BreakBeforeBinaryOperators = true; |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 305 | Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 306 | Style.BreakConstructorInitializersBeforeComma = true; |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 307 | Style.ColumnLimit = 0; |
Daniel Jasper | e8b10d3 | 2013-07-26 16:56:36 +0000 | [diff] [blame] | 308 | Style.IndentWidth = 4; |
Daniel Jasper | eff18b9 | 2013-07-31 23:16:02 +0000 | [diff] [blame] | 309 | Style.NamespaceIndentation = FormatStyle::NI_Inner; |
Daniel Jasper | e05dc6d | 2013-07-24 13:10:59 +0000 | [diff] [blame] | 310 | Style.PointerBindsToType = true; |
| 311 | return Style; |
| 312 | } |
| 313 | |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 314 | bool getPredefinedStyle(StringRef Name, FormatStyle *Style) { |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 315 | if (Name.equals_lower("llvm")) |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 316 | *Style = getLLVMStyle(); |
| 317 | else if (Name.equals_lower("chromium")) |
| 318 | *Style = getChromiumStyle(); |
| 319 | else if (Name.equals_lower("mozilla")) |
| 320 | *Style = getMozillaStyle(); |
| 321 | else if (Name.equals_lower("google")) |
| 322 | *Style = getGoogleStyle(); |
Daniel Jasper | e05dc6d | 2013-07-24 13:10:59 +0000 | [diff] [blame] | 323 | else if (Name.equals_lower("webkit")) |
| 324 | *Style = getWebKitStyle(); |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 325 | else |
| 326 | return false; |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 327 | |
Alexander Kornienko | 885f87b | 2013-05-19 00:53:30 +0000 | [diff] [blame] | 328 | return true; |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 329 | } |
| 330 | |
| 331 | llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { |
Alexander Kornienko | 107db3c | 2013-05-20 15:18:01 +0000 | [diff] [blame] | 332 | if (Text.trim().empty()) |
| 333 | return llvm::make_error_code(llvm::errc::invalid_argument); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 334 | llvm::yaml::Input Input(Text); |
| 335 | Input >> *Style; |
| 336 | return Input.error(); |
| 337 | } |
| 338 | |
| 339 | std::string configurationAsText(const FormatStyle &Style) { |
| 340 | std::string Text; |
| 341 | llvm::raw_string_ostream Stream(Text); |
| 342 | llvm::yaml::Output Output(Stream); |
| 343 | // We use the same mapping method for input and output, so we need a non-const |
| 344 | // reference here. |
| 345 | FormatStyle NonConstStyle = Style; |
| 346 | Output << NonConstStyle; |
Alexander Kornienko | 2b6acb6 | 2013-05-13 12:56:35 +0000 | [diff] [blame] | 347 | return Stream.str(); |
Alexander Kornienko | d71ec16 | 2013-05-07 15:32:14 +0000 | [diff] [blame] | 348 | } |
| 349 | |
Craig Topper | 83f81d7 | 2013-06-30 22:29:28 +0000 | [diff] [blame] | 350 | namespace { |
| 351 | |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 352 | class NoColumnLimitFormatter { |
| 353 | public: |
Daniel Jasper | 34f3d05 | 2013-08-21 08:39:01 +0000 | [diff] [blame] | 354 | NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {} |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 355 | |
| 356 | /// \brief Formats the line starting at \p State, simply keeping all of the |
| 357 | /// input's line breaking decisions. |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 358 | void format(unsigned FirstIndent, const AnnotatedLine *Line) { |
Daniel Jasper | b77d741 | 2013-09-06 07:54:20 +0000 | [diff] [blame] | 359 | LineState State = |
| 360 | Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false); |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 361 | while (State.NextToken != NULL) { |
| 362 | bool Newline = |
| 363 | Indenter->mustBreak(State) || |
| 364 | (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); |
| 365 | Indenter->addTokenToState(State, Newline, /*DryRun=*/false); |
| 366 | } |
| 367 | } |
Daniel Jasper | 34f3d05 | 2013-08-21 08:39:01 +0000 | [diff] [blame] | 368 | |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 369 | private: |
| 370 | ContinuationIndenter *Indenter; |
| 371 | }; |
| 372 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 373 | class UnwrappedLineFormatter { |
| 374 | public: |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 375 | UnwrappedLineFormatter(SourceManager &SourceMgr, |
| 376 | SmallVectorImpl<CharSourceRange> &Ranges, |
| 377 | ContinuationIndenter *Indenter, |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 378 | WhitespaceManager *Whitespaces, |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 379 | const FormatStyle &Style) |
| 380 | : SourceMgr(SourceMgr), Ranges(Ranges), Indenter(Indenter), |
| 381 | Whitespaces(Whitespaces), Style(Style) {} |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 382 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 383 | unsigned format(SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun, |
| 384 | int AdditionalIndent = 0) { |
| 385 | assert(!Lines.empty()); |
| 386 | unsigned Penalty = 0; |
| 387 | std::vector<int> IndentForLevel; |
| 388 | for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i) |
| 389 | IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); |
| 390 | bool PreviousLineWasTouched = false; |
| 391 | const AnnotatedLine *PreviousLine = NULL; |
| 392 | bool FormatPPDirective = false; |
| 393 | for (SmallVectorImpl<AnnotatedLine *>::iterator I = Lines.begin(), |
| 394 | E = Lines.end(); |
| 395 | I != E; ++I) { |
| 396 | const AnnotatedLine &TheLine = **I; |
| 397 | const FormatToken *FirstTok = TheLine.First; |
| 398 | int Offset = getIndentOffset(*FirstTok); |
| 399 | |
| 400 | // Check whether this line is part of a formatted preprocessor directive. |
| 401 | if (FirstTok->HasUnescapedNewline) |
| 402 | FormatPPDirective = false; |
| 403 | if (!FormatPPDirective && TheLine.InPPDirective && |
| 404 | (touchesLine(TheLine) || touchesPPDirective(I + 1, E))) |
| 405 | FormatPPDirective = true; |
| 406 | |
| 407 | // Determine indent and try to merge multiple unwrapped lines. |
| 408 | while (IndentForLevel.size() <= TheLine.Level) |
| 409 | IndentForLevel.push_back(-1); |
| 410 | IndentForLevel.resize(TheLine.Level + 1); |
| 411 | unsigned Indent = getIndent(IndentForLevel, TheLine.Level); |
| 412 | if (static_cast<int>(Indent) + Offset >= 0) |
| 413 | Indent += Offset; |
| 414 | if (!DryRun) |
| 415 | tryFitMultipleLinesInOne(Indent, I, E); |
| 416 | |
| 417 | bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0; |
| 418 | if (TheLine.First->is(tok::eof)) { |
| 419 | if (PreviousLineWasTouched && !DryRun) { |
| 420 | unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u); |
| 421 | Whitespaces->replaceWhitespace(*TheLine.First, Newlines, |
| 422 | /*IndentLevel=*/0, /*Spaces=*/0, |
| 423 | /*TargetColumn=*/0); |
| 424 | } |
| 425 | } else if (TheLine.Type != LT_Invalid && |
| 426 | (WasMoved || FormatPPDirective || touchesLine(TheLine))) { |
| 427 | unsigned LevelIndent = |
| 428 | getIndent(IndentForLevel, TheLine.Level); |
| 429 | if (FirstTok->WhitespaceRange.isValid()) { |
| 430 | if (!DryRun) |
| 431 | formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, |
| 432 | Indent, TheLine.InPPDirective); |
| 433 | } else { |
| 434 | Indent = LevelIndent = FirstTok->OriginalColumn; |
| 435 | } |
| 436 | |
| 437 | // If everything fits on a single line, just put it there. |
| 438 | unsigned ColumnLimit = Style.ColumnLimit; |
| 439 | if (I + 1 != E) { |
| 440 | AnnotatedLine *NextLine = *(I + 1); |
| 441 | if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline) |
| 442 | ColumnLimit = getColumnLimit(TheLine.InPPDirective); |
| 443 | } |
| 444 | |
| 445 | if (TheLine.Last->TotalLength + Indent <= ColumnLimit) { |
| 446 | LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun); |
| 447 | while (State.NextToken != NULL) |
| 448 | Indenter->addTokenToState(State, /*Newline=*/false, DryRun); |
| 449 | } else if (Style.ColumnLimit == 0) { |
| 450 | NoColumnLimitFormatter Formatter(Indenter); |
| 451 | if (!DryRun) |
| 452 | Formatter.format(Indent, &TheLine); |
| 453 | } else { |
| 454 | Penalty += format(TheLine, Indent, DryRun); |
| 455 | } |
| 456 | |
| 457 | IndentForLevel[TheLine.Level] = LevelIndent; |
| 458 | PreviousLineWasTouched = true; |
| 459 | } else { |
| 460 | // Format the first token if necessary, and notify the WhitespaceManager |
| 461 | // about the unchanged whitespace. |
| 462 | for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) { |
| 463 | if (Tok == TheLine.First && |
| 464 | (Tok->NewlinesBefore > 0 || Tok->IsFirst)) { |
| 465 | unsigned LevelIndent = Tok->OriginalColumn; |
| 466 | if (!DryRun) { |
| 467 | // Remove trailing whitespace of the previous line if it was |
| 468 | // touched. |
| 469 | if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) { |
| 470 | formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent, |
| 471 | TheLine.InPPDirective); |
| 472 | } else { |
| 473 | Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | if (static_cast<int>(LevelIndent) - Offset >= 0) |
| 478 | LevelIndent -= Offset; |
| 479 | if (Tok->isNot(tok::comment)) |
| 480 | IndentForLevel[TheLine.Level] = LevelIndent; |
| 481 | } else if (!DryRun) { |
| 482 | Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); |
| 483 | } |
| 484 | } |
| 485 | // If we did not reformat this unwrapped line, the column at the end of |
| 486 | // the last token is unchanged - thus, we can calculate the end of the |
| 487 | // last token. |
| 488 | PreviousLineWasTouched = false; |
| 489 | } |
| 490 | if (!DryRun) { |
| 491 | for (FormatToken *Tok = TheLine.First; Tok != NULL; Tok = Tok->Next) { |
| 492 | Tok->Finalized = true; |
| 493 | } |
| 494 | } |
| 495 | PreviousLine = *I; |
| 496 | } |
| 497 | return Penalty; |
| 498 | } |
| 499 | |
| 500 | private: |
| 501 | /// \brief Formats an \c AnnotatedLine and returns the penalty. |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 502 | /// |
| 503 | /// If \p DryRun is \c false, directly applies the changes. |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 504 | unsigned format(const AnnotatedLine &Line, unsigned FirstIndent, |
| 505 | bool DryRun) { |
Daniel Jasper | b77d741 | 2013-09-06 07:54:20 +0000 | [diff] [blame] | 506 | LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 507 | |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 508 | // If the ObjC method declaration does not fit on a line, we should format |
| 509 | // it with one arg per line. |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 510 | if (State.Line->Type == LT_ObjCMethodDecl) |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 511 | State.Stack.back().BreakBeforeParameter = true; |
| 512 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 513 | // Find best solution in solution space. |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 514 | return analyzeSolutionSpace(State, DryRun); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 515 | } |
| 516 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 517 | /// \brief An edge in the solution space from \c Previous->State to \c State, |
| 518 | /// inserting a newline dependent on the \c NewLine. |
| 519 | struct StateNode { |
| 520 | StateNode(const LineState &State, bool NewLine, StateNode *Previous) |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 521 | : State(State), NewLine(NewLine), Previous(Previous) {} |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 522 | LineState State; |
| 523 | bool NewLine; |
| 524 | StateNode *Previous; |
| 525 | }; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 526 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 527 | /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. |
| 528 | /// |
| 529 | /// In case of equal penalties, we want to prefer states that were inserted |
| 530 | /// first. During state generation we make sure that we insert states first |
| 531 | /// that break the line as late as possible. |
| 532 | typedef std::pair<unsigned, unsigned> OrderedPenalty; |
| 533 | |
| 534 | /// \brief An item in the prioritized BFS search queue. The \c StateNode's |
| 535 | /// \c State has the given \c OrderedPenalty. |
| 536 | typedef std::pair<OrderedPenalty, StateNode *> QueueItem; |
| 537 | |
| 538 | /// \brief The BFS queue type. |
| 539 | typedef std::priority_queue<QueueItem, std::vector<QueueItem>, |
| 540 | std::greater<QueueItem> > QueueType; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 541 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 542 | /// \brief Get the offset of the line relatively to the level. |
| 543 | /// |
| 544 | /// For example, 'public:' labels in classes are offset by 1 or 2 |
| 545 | /// characters to the left from their level. |
| 546 | int getIndentOffset(const FormatToken &RootToken) { |
| 547 | if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier()) |
| 548 | return Style.AccessModifierOffset; |
| 549 | return 0; |
| 550 | } |
| 551 | |
| 552 | /// \brief Add a new line and the required indent before the first Token |
| 553 | /// of the \c UnwrappedLine if there was no structural parsing error. |
| 554 | void formatFirstToken(FormatToken &RootToken, |
| 555 | const AnnotatedLine *PreviousLine, unsigned IndentLevel, |
| 556 | unsigned Indent, bool InPPDirective) { |
| 557 | unsigned Newlines = |
| 558 | std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); |
| 559 | // Remove empty lines before "}" where applicable. |
| 560 | if (RootToken.is(tok::r_brace) && |
| 561 | (!RootToken.Next || |
| 562 | (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) |
| 563 | Newlines = std::min(Newlines, 1u); |
| 564 | if (Newlines == 0 && !RootToken.IsFirst) |
| 565 | Newlines = 1; |
| 566 | |
| 567 | // Insert extra new line before access specifiers. |
| 568 | if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && |
| 569 | RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) |
| 570 | ++Newlines; |
| 571 | |
| 572 | // Remove empty lines after access specifiers. |
| 573 | if (PreviousLine && PreviousLine->First->isAccessSpecifier()) |
| 574 | Newlines = std::min(1u, Newlines); |
| 575 | |
| 576 | Whitespaces->replaceWhitespace( |
| 577 | RootToken, Newlines, IndentLevel, Indent, Indent, |
| 578 | InPPDirective && !RootToken.HasUnescapedNewline); |
| 579 | } |
| 580 | |
| 581 | /// \brief Get the indent of \p Level from \p IndentForLevel. |
| 582 | /// |
| 583 | /// \p IndentForLevel must contain the indent for the level \c l |
| 584 | /// at \p IndentForLevel[l], or a value < 0 if the indent for |
| 585 | /// that level is unknown. |
| 586 | unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) { |
| 587 | if (IndentForLevel[Level] != -1) |
| 588 | return IndentForLevel[Level]; |
| 589 | if (Level == 0) |
| 590 | return 0; |
| 591 | return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; |
| 592 | } |
| 593 | |
| 594 | /// \brief Tries to merge lines into one. |
| 595 | /// |
| 596 | /// This will change \c Line and \c AnnotatedLine to contain the merged line, |
| 597 | /// if possible; note that \c I will be incremented when lines are merged. |
| 598 | void tryFitMultipleLinesInOne(unsigned Indent, |
| 599 | SmallVectorImpl<AnnotatedLine *>::iterator &I, |
| 600 | SmallVectorImpl<AnnotatedLine *>::iterator E) { |
| 601 | // We can never merge stuff if there are trailing line comments. |
| 602 | AnnotatedLine *TheLine = *I; |
| 603 | if (TheLine->Last->Type == TT_LineComment) |
| 604 | return; |
| 605 | |
| 606 | if (Indent > Style.ColumnLimit) |
| 607 | return; |
| 608 | |
| 609 | unsigned Limit = Style.ColumnLimit - Indent; |
| 610 | // If we already exceed the column limit, we set 'Limit' to 0. The different |
| 611 | // tryMerge..() functions can then decide whether to still do merging. |
| 612 | Limit = TheLine->Last->TotalLength > Limit |
| 613 | ? 0 |
| 614 | : Limit - TheLine->Last->TotalLength; |
| 615 | |
| 616 | if (I + 1 == E || (*(I + 1))->Type == LT_Invalid) |
| 617 | return; |
| 618 | |
| 619 | if (TheLine->Last->is(tok::l_brace)) { |
| 620 | tryMergeSimpleBlock(I, E, Limit); |
| 621 | } else if (Style.AllowShortIfStatementsOnASingleLine && |
| 622 | TheLine->First->is(tok::kw_if)) { |
| 623 | tryMergeSimpleControlStatement(I, E, Limit); |
| 624 | } else if (Style.AllowShortLoopsOnASingleLine && |
| 625 | TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { |
| 626 | tryMergeSimpleControlStatement(I, E, Limit); |
| 627 | } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline || |
| 628 | TheLine->First->IsFirst)) { |
| 629 | tryMergeSimplePPDirective(I, E, Limit); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I, |
| 634 | SmallVectorImpl<AnnotatedLine *>::iterator E, |
| 635 | unsigned Limit) { |
| 636 | if (Limit == 0) |
| 637 | return; |
| 638 | AnnotatedLine &Line = **I; |
| 639 | if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline) |
| 640 | return; |
| 641 | if (I + 2 != E && (*(I + 2))->InPPDirective && |
| 642 | !(*(I + 2))->First->HasUnescapedNewline) |
| 643 | return; |
| 644 | if (1 + (*(I + 1))->Last->TotalLength > Limit) |
| 645 | return; |
| 646 | join(Line, **(++I)); |
| 647 | } |
| 648 | |
| 649 | void |
| 650 | tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I, |
| 651 | SmallVectorImpl<AnnotatedLine *>::iterator E, |
| 652 | unsigned Limit) { |
| 653 | if (Limit == 0) |
| 654 | return; |
| 655 | if (Style.BreakBeforeBraces == FormatStyle::BS_Allman && |
| 656 | (*(I + 1))->First->is(tok::l_brace)) |
| 657 | return; |
| 658 | if ((*(I + 1))->InPPDirective != (*I)->InPPDirective || |
| 659 | ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline)) |
| 660 | return; |
| 661 | AnnotatedLine &Line = **I; |
| 662 | if (Line.Last->isNot(tok::r_paren)) |
| 663 | return; |
| 664 | if (1 + (*(I + 1))->Last->TotalLength > Limit) |
| 665 | return; |
| 666 | if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, |
| 667 | tok::kw_while) || |
| 668 | (*(I + 1))->First->Type == TT_LineComment) |
| 669 | return; |
| 670 | // Only inline simple if's (no nested if or else). |
| 671 | if (I + 2 != E && Line.First->is(tok::kw_if) && |
| 672 | (*(I + 2))->First->is(tok::kw_else)) |
| 673 | return; |
| 674 | join(Line, **(++I)); |
| 675 | } |
| 676 | |
| 677 | void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I, |
| 678 | SmallVectorImpl<AnnotatedLine *>::iterator E, |
| 679 | unsigned Limit) { |
| 680 | // No merging if the brace already is on the next line. |
| 681 | if (Style.BreakBeforeBraces != FormatStyle::BS_Attach) |
| 682 | return; |
| 683 | |
| 684 | // First, check that the current line allows merging. This is the case if |
| 685 | // we're not in a control flow statement and the last token is an opening |
| 686 | // brace. |
| 687 | AnnotatedLine &Line = **I; |
| 688 | if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace, |
| 689 | tok::kw_else, tok::kw_try, tok::kw_catch, |
| 690 | tok::kw_for, |
| 691 | // This gets rid of all ObjC @ keywords and methods. |
| 692 | tok::at, tok::minus, tok::plus)) |
| 693 | return; |
| 694 | |
| 695 | FormatToken *Tok = (*(I + 1))->First; |
| 696 | if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && |
| 697 | (Tok->getNextNonComment() == NULL || |
| 698 | Tok->getNextNonComment()->is(tok::semi))) { |
| 699 | // We merge empty blocks even if the line exceeds the column limit. |
| 700 | Tok->SpacesRequiredBefore = 0; |
| 701 | Tok->CanBreakBefore = true; |
| 702 | join(Line, **(I + 1)); |
| 703 | I += 1; |
| 704 | } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) { |
| 705 | // Check that we still have three lines and they fit into the limit. |
| 706 | if (I + 2 == E || (*(I + 2))->Type == LT_Invalid || |
| 707 | !nextTwoLinesFitInto(I, Limit)) |
| 708 | return; |
| 709 | |
| 710 | // Second, check that the next line does not contain any braces - if it |
| 711 | // does, readability declines when putting it into a single line. |
| 712 | if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore) |
| 713 | return; |
| 714 | do { |
| 715 | if (Tok->isOneOf(tok::l_brace, tok::r_brace)) |
| 716 | return; |
| 717 | Tok = Tok->Next; |
| 718 | } while (Tok != NULL); |
| 719 | |
| 720 | // Last, check that the third line contains a single closing brace. |
| 721 | Tok = (*(I + 2))->First; |
| 722 | if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) || |
| 723 | Tok->MustBreakBefore) |
| 724 | return; |
| 725 | |
| 726 | join(Line, **(I + 1)); |
| 727 | join(Line, **(I + 2)); |
| 728 | I += 2; |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I, |
| 733 | unsigned Limit) { |
| 734 | return 1 + (*(I + 1))->Last->TotalLength + 1 + |
| 735 | (*(I + 2))->Last->TotalLength <= |
| 736 | Limit; |
| 737 | } |
| 738 | |
| 739 | void join(AnnotatedLine &A, const AnnotatedLine &B) { |
| 740 | assert(!A.Last->Next); |
| 741 | assert(!B.First->Previous); |
| 742 | A.Last->Next = B.First; |
| 743 | B.First->Previous = A.Last; |
| 744 | unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; |
| 745 | for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { |
| 746 | Tok->TotalLength += LengthA; |
| 747 | A.Last = Tok; |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | unsigned getColumnLimit(bool InPPDirective) const { |
| 752 | // In preprocessor directives reserve two chars for trailing " \" |
| 753 | return Style.ColumnLimit - (InPPDirective ? 2 : 0); |
| 754 | } |
| 755 | |
| 756 | bool touchesRanges(const CharSourceRange &Range) { |
| 757 | for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(), |
| 758 | E = Ranges.end(); |
| 759 | I != E; ++I) { |
| 760 | if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) && |
| 761 | !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin())) |
| 762 | return true; |
| 763 | } |
| 764 | return false; |
| 765 | } |
| 766 | |
| 767 | bool touchesLine(const AnnotatedLine &TheLine) { |
| 768 | const FormatToken *First = TheLine.First; |
| 769 | const FormatToken *Last = TheLine.Last; |
| 770 | CharSourceRange LineRange = CharSourceRange::getCharRange( |
| 771 | First->WhitespaceRange.getBegin().getLocWithOffset( |
| 772 | First->LastNewlineOffset), |
| 773 | Last->getStartOfNonWhitespace().getLocWithOffset( |
| 774 | Last->TokenText.size() - 1)); |
| 775 | return touchesRanges(LineRange); |
| 776 | } |
| 777 | |
| 778 | bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 779 | SmallVectorImpl<AnnotatedLine *>::const_iterator E) { |
| 780 | for (; I != E; ++I) { |
| 781 | if ((*I)->First->HasUnescapedNewline) |
| 782 | return false; |
| 783 | if (touchesLine(**I)) |
| 784 | return true; |
| 785 | } |
| 786 | return false; |
| 787 | } |
| 788 | |
| 789 | bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) { |
| 790 | const FormatToken *First = TheLine.First; |
| 791 | CharSourceRange LineRange = CharSourceRange::getCharRange( |
| 792 | First->WhitespaceRange.getBegin(), |
| 793 | First->WhitespaceRange.getBegin().getLocWithOffset( |
| 794 | First->LastNewlineOffset)); |
| 795 | return touchesRanges(LineRange); |
| 796 | } |
| 797 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 798 | /// \brief Analyze the entire solution space starting from \p InitialState. |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 799 | /// |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 800 | /// This implements a variant of Dijkstra's algorithm on the graph that spans |
| 801 | /// the solution space (\c LineStates are the nodes). The algorithm tries to |
| 802 | /// find the shortest path (the one with lowest penalty) from \p InitialState |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 803 | /// to a state where all tokens are placed. Returns the penalty. |
| 804 | /// |
| 805 | /// If \p DryRun is \c false, directly applies the changes. |
| 806 | unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) { |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 807 | std::set<LineState> Seen; |
| 808 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 809 | // Increasing count of \c StateNode items we have created. This is used to |
| 810 | // create a deterministic order independent of the container. |
| 811 | unsigned Count = 0; |
| 812 | QueueType Queue; |
| 813 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 814 | // Insert start element into queue. |
Daniel Jasper | fc75908 | 2013-02-14 14:26:07 +0000 | [diff] [blame] | 815 | StateNode *Node = |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 816 | new (Allocator.Allocate()) StateNode(InitialState, false, NULL); |
| 817 | Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); |
| 818 | ++Count; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 819 | |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 820 | unsigned Penalty = 0; |
| 821 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 822 | // While not empty, take first element and follow edges. |
| 823 | while (!Queue.empty()) { |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 824 | Penalty = Queue.top().first.first; |
Daniel Jasper | fc75908 | 2013-02-14 14:26:07 +0000 | [diff] [blame] | 825 | StateNode *Node = Queue.top().second; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 826 | if (Node->State.NextToken == NULL) { |
Alexander Kornienko | dd25631 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 827 | DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 828 | break; |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 829 | } |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 830 | Queue.pop(); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 831 | |
Daniel Jasper | 54b4e44 | 2013-05-22 05:27:42 +0000 | [diff] [blame] | 832 | // Cut off the analysis of certain solutions if the analysis gets too |
| 833 | // complex. See description of IgnoreStackForComparison. |
| 834 | if (Count > 10000) |
| 835 | Node->State.IgnoreStackForComparison = true; |
| 836 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 837 | if (!Seen.insert(Node->State).second) |
| 838 | // State already examined with lower penalty. |
| 839 | continue; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 840 | |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 841 | FormatDecision LastFormat = Node->State.NextToken->Decision; |
| 842 | if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 843 | addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 844 | if (LastFormat == FD_Unformatted || LastFormat == FD_Break) |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 845 | addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 846 | } |
| 847 | |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 848 | if (Queue.empty()) { |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 849 | // We were unable to find a solution, do nothing. |
| 850 | // FIXME: Add diagnostic? |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 851 | DEBUG(llvm::dbgs() << "Could not find a solution.\n"); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 852 | return 0; |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 853 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 854 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 855 | // Reconstruct the solution. |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 856 | if (!DryRun) |
| 857 | reconstructPath(InitialState, Queue.top().second); |
| 858 | |
Alexander Kornienko | dd25631 | 2013-05-10 11:56:10 +0000 | [diff] [blame] | 859 | DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); |
| 860 | DEBUG(llvm::dbgs() << "---\n"); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 861 | |
| 862 | return Penalty; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 863 | } |
| 864 | |
| 865 | void reconstructPath(LineState &State, StateNode *Current) { |
Manuel Klimek | 9c333b9 | 2013-05-29 15:10:11 +0000 | [diff] [blame] | 866 | std::deque<StateNode *> Path; |
| 867 | // We do not need a break before the initial token. |
| 868 | while (Current->Previous) { |
| 869 | Path.push_front(Current); |
| 870 | Current = Current->Previous; |
| 871 | } |
| 872 | for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); |
| 873 | I != E; ++I) { |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 874 | unsigned Penalty = 0; |
| 875 | formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); |
| 876 | Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); |
| 877 | |
Manuel Klimek | 9c333b9 | 2013-05-29 15:10:11 +0000 | [diff] [blame] | 878 | DEBUG({ |
| 879 | if ((*I)->NewLine) { |
Daniel Jasper | d4a03db | 2013-08-22 15:00:41 +0000 | [diff] [blame] | 880 | llvm::dbgs() << "Penalty for placing " |
Manuel Klimek | 9c333b9 | 2013-05-29 15:10:11 +0000 | [diff] [blame] | 881 | << (*I)->Previous->State.NextToken->Tok.getName() << ": " |
Daniel Jasper | d4a03db | 2013-08-22 15:00:41 +0000 | [diff] [blame] | 882 | << Penalty << "\n"; |
Manuel Klimek | 9c333b9 | 2013-05-29 15:10:11 +0000 | [diff] [blame] | 883 | } |
| 884 | }); |
Manuel Klimek | 9c333b9 | 2013-05-29 15:10:11 +0000 | [diff] [blame] | 885 | } |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 886 | } |
| 887 | |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 888 | /// \brief Add the following state to the analysis queue \c Queue. |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 889 | /// |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 890 | /// Assume the current state is \p PreviousNode and has been reached with a |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 891 | /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 892 | void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 893 | bool NewLine, unsigned *Count, QueueType *Queue) { |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 894 | if (NewLine && !Indenter->canBreak(PreviousNode->State)) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 895 | return; |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 896 | if (!NewLine && Indenter->mustBreak(PreviousNode->State)) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 897 | return; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 898 | |
| 899 | StateNode *Node = new (Allocator.Allocate()) |
| 900 | StateNode(PreviousNode->State, NewLine, PreviousNode); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 901 | if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) |
| 902 | return; |
| 903 | |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 904 | Penalty += Indenter->addTokenToState(Node->State, NewLine, true); |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 905 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 906 | Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); |
| 907 | ++(*Count); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 908 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 909 | |
Daniel Jasper | 1a925bc | 2013-09-05 10:48:50 +0000 | [diff] [blame] | 910 | /// \brief If the \p State's next token is an r_brace closing a nested block, |
| 911 | /// format the nested block before it. |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 912 | /// |
| 913 | /// Returns \c true if all children could be placed successfully and adapts |
| 914 | /// \p Penalty as well as \p State. If \p DryRun is false, also directly |
| 915 | /// creates changes using \c Whitespaces. |
| 916 | /// |
| 917 | /// The crucial idea here is that children always get formatted upon |
| 918 | /// encountering the closing brace right after the nested block. Now, if we |
| 919 | /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is |
| 920 | /// \c false), the entire block has to be kept on the same line (which is only |
| 921 | /// possible if it fits on the line, only contains a single statement, etc. |
| 922 | /// |
| 923 | /// If \p NewLine is true, we format the nested block on separate lines, i.e. |
| 924 | /// break after the "{", format all lines with correct indentation and the put |
| 925 | /// the closing "}" on yet another new line. |
| 926 | /// |
| 927 | /// This enables us to keep the simple structure of the |
| 928 | /// \c UnwrappedLineFormatter, where we only have two options for each token: |
| 929 | /// break or don't break. |
| 930 | bool formatChildren(LineState &State, bool NewLine, bool DryRun, |
| 931 | unsigned &Penalty) { |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 932 | FormatToken &Previous = *State.NextToken->Previous; |
Daniel Jasper | 15eef85 | 2013-10-20 17:28:32 +0000 | [diff] [blame] | 933 | const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); |
| 934 | if (!LBrace || LBrace->isNot(tok::l_brace) || |
| 935 | LBrace->BlockKind != BK_Block || Previous.Children.size() == 0) |
Daniel Jasper | 1a925bc | 2013-09-05 10:48:50 +0000 | [diff] [blame] | 936 | // The previous token does not open a block. Nothing to do. We don't |
| 937 | // assert so that we can simply call this function for all tokens. |
Daniel Jasper | 2f0a020 | 2013-09-06 08:54:24 +0000 | [diff] [blame] | 938 | return true; |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 939 | |
| 940 | if (NewLine) { |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 941 | int AdditionalIndent = State.Stack.back().Indent - |
| 942 | Previous.Children[0]->Level * Style.IndentWidth; |
| 943 | Penalty += format(Previous.Children, DryRun, AdditionalIndent); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 944 | return true; |
| 945 | } |
| 946 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 947 | // Cannot merge multiple statements into a single line. |
Daniel Jasper | 15eef85 | 2013-10-20 17:28:32 +0000 | [diff] [blame] | 948 | if (Previous.Children.size() > 1) |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 949 | return false; |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 950 | |
| 951 | // We can't put the closing "}" on a line with a trailing comment. |
Daniel Jasper | 15eef85 | 2013-10-20 17:28:32 +0000 | [diff] [blame] | 952 | if (Previous.Children[0]->Last->isTrailingComment()) |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 953 | return false; |
| 954 | |
| 955 | if (!DryRun) { |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 956 | Whitespaces->replaceWhitespace( |
Daniel Jasper | 15eef85 | 2013-10-20 17:28:32 +0000 | [diff] [blame] | 957 | *Previous.Children[0]->First, |
Alexander Kornienko | f0fc89c | 2013-10-14 00:46:35 +0000 | [diff] [blame] | 958 | /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1, |
Alexander Kornienko | 3d9ffcf | 2013-09-27 16:14:22 +0000 | [diff] [blame] | 959 | /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 960 | } |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 961 | Penalty += format(*Previous.Children[0], State.Column + 1, DryRun); |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 962 | |
Daniel Jasper | 15eef85 | 2013-10-20 17:28:32 +0000 | [diff] [blame] | 963 | State.Column += 1 + Previous.Children[0]->Last->TotalLength; |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 964 | return true; |
| 965 | } |
| 966 | |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 967 | SourceManager &SourceMgr; |
| 968 | SmallVectorImpl<CharSourceRange> &Ranges; |
Daniel Jasper | 6b2afe4 | 2013-08-16 11:20:30 +0000 | [diff] [blame] | 969 | ContinuationIndenter *Indenter; |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 970 | WhitespaceManager *Whitespaces; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 971 | FormatStyle Style; |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 972 | |
| 973 | llvm::SpecificBumpPtrAllocator<StateNode> Allocator; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 974 | }; |
| 975 | |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 976 | class FormatTokenLexer { |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 977 | public: |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 978 | FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style, |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 979 | encoding::Encoding Encoding) |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 980 | : FormatTok(NULL), GreaterStashed(false), Column(0), |
| 981 | TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style), |
| 982 | IdentTable(getFormattingLangOpts()), Encoding(Encoding) { |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 983 | Lex.SetKeepWhitespaceMode(true); |
| 984 | } |
| 985 | |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 986 | ArrayRef<FormatToken *> lex() { |
| 987 | assert(Tokens.empty()); |
| 988 | do { |
| 989 | Tokens.push_back(getNextToken()); |
Alexander Kornienko | 2c2f729 | 2013-09-16 20:20:49 +0000 | [diff] [blame] | 990 | maybeJoinPreviousTokens(); |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 991 | } while (Tokens.back()->Tok.isNot(tok::eof)); |
| 992 | return Tokens; |
| 993 | } |
| 994 | |
| 995 | IdentifierTable &getIdentTable() { return IdentTable; } |
| 996 | |
| 997 | private: |
Alexander Kornienko | 2c2f729 | 2013-09-16 20:20:49 +0000 | [diff] [blame] | 998 | void maybeJoinPreviousTokens() { |
| 999 | if (Tokens.size() < 4) |
| 1000 | return; |
| 1001 | FormatToken *Last = Tokens.back(); |
| 1002 | if (!Last->is(tok::r_paren)) |
| 1003 | return; |
| 1004 | |
| 1005 | FormatToken *String = Tokens[Tokens.size() - 2]; |
| 1006 | if (!String->is(tok::string_literal) || String->IsMultiline) |
| 1007 | return; |
| 1008 | |
| 1009 | if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) |
| 1010 | return; |
| 1011 | |
| 1012 | FormatToken *Macro = Tokens[Tokens.size() - 4]; |
| 1013 | if (Macro->TokenText != "_T") |
| 1014 | return; |
| 1015 | |
| 1016 | const char *Start = Macro->TokenText.data(); |
| 1017 | const char *End = Last->TokenText.data() + Last->TokenText.size(); |
| 1018 | String->TokenText = StringRef(Start, End - Start); |
| 1019 | String->IsFirst = Macro->IsFirst; |
| 1020 | String->LastNewlineOffset = Macro->LastNewlineOffset; |
| 1021 | String->WhitespaceRange = Macro->WhitespaceRange; |
| 1022 | String->OriginalColumn = Macro->OriginalColumn; |
| 1023 | String->ColumnWidth = encoding::columnWidthWithTabs( |
| 1024 | String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); |
| 1025 | |
| 1026 | Tokens.pop_back(); |
| 1027 | Tokens.pop_back(); |
| 1028 | Tokens.pop_back(); |
| 1029 | Tokens.back() = String; |
| 1030 | } |
| 1031 | |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1032 | FormatToken *getNextToken() { |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1033 | if (GreaterStashed) { |
Manuel Klimek | dcb3f2a | 2013-05-28 13:42:28 +0000 | [diff] [blame] | 1034 | // Create a synthesized second '>' token. |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1035 | // FIXME: Increment Column and set OriginalColumn. |
Manuel Klimek | dcb3f2a | 2013-05-28 13:42:28 +0000 | [diff] [blame] | 1036 | Token Greater = FormatTok->Tok; |
| 1037 | FormatTok = new (Allocator.Allocate()) FormatToken; |
| 1038 | FormatTok->Tok = Greater; |
Manuel Klimek | ad3094b | 2013-05-23 10:56:37 +0000 | [diff] [blame] | 1039 | SourceLocation GreaterLocation = |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1040 | FormatTok->Tok.getLocation().getLocWithOffset(1); |
| 1041 | FormatTok->WhitespaceRange = |
| 1042 | SourceRange(GreaterLocation, GreaterLocation); |
Alexander Kornienko | 54e6c9d | 2013-06-07 17:45:07 +0000 | [diff] [blame] | 1043 | FormatTok->TokenText = ">"; |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1044 | FormatTok->ColumnWidth = 1; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1045 | GreaterStashed = false; |
| 1046 | return FormatTok; |
| 1047 | } |
| 1048 | |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1049 | FormatTok = new (Allocator.Allocate()) FormatToken; |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1050 | readRawToken(*FormatTok); |
Manuel Klimek | de008c0 | 2013-05-27 15:23:34 +0000 | [diff] [blame] | 1051 | SourceLocation WhitespaceStart = |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1052 | FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); |
Manuel Klimek | ad3094b | 2013-05-23 10:56:37 +0000 | [diff] [blame] | 1053 | if (SourceMgr.getFileOffset(WhitespaceStart) == 0) |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1054 | FormatTok->IsFirst = true; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1055 | |
| 1056 | // Consume and record whitespace until we find a significant token. |
Manuel Klimek | de008c0 | 2013-05-27 15:23:34 +0000 | [diff] [blame] | 1057 | unsigned WhitespaceLength = TrailingWhitespace; |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1058 | while (FormatTok->Tok.is(tok::unknown)) { |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1059 | for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) { |
| 1060 | switch (FormatTok->TokenText[i]) { |
| 1061 | case '\n': |
| 1062 | ++FormatTok->NewlinesBefore; |
| 1063 | // FIXME: This is technically incorrect, as it could also |
| 1064 | // be a literal backslash at the end of the line. |
Alexander Kornienko | 73d845c | 2013-09-11 12:25:57 +0000 | [diff] [blame] | 1065 | if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' && |
| 1066 | (FormatTok->TokenText[i - 1] != '\r' || i == 1 || |
| 1067 | FormatTok->TokenText[i - 2] != '\\'))) |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1068 | FormatTok->HasUnescapedNewline = true; |
| 1069 | FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; |
| 1070 | Column = 0; |
| 1071 | break; |
Daniel Jasper | 1d82b1a | 2013-10-11 19:45:02 +0000 | [diff] [blame] | 1072 | case '\r': |
| 1073 | case '\f': |
| 1074 | case '\v': |
| 1075 | Column = 0; |
| 1076 | break; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1077 | case ' ': |
| 1078 | ++Column; |
| 1079 | break; |
| 1080 | case '\t': |
Alexander Kornienko | 0b62cc3 | 2013-09-05 14:08:34 +0000 | [diff] [blame] | 1081 | Column += Style.TabWidth - Column % Style.TabWidth; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1082 | break; |
Daniel Jasper | 1d82b1a | 2013-10-11 19:45:02 +0000 | [diff] [blame] | 1083 | case '\\': |
| 1084 | ++Column; |
| 1085 | if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' && |
| 1086 | FormatTok->TokenText[i + 1] != '\n')) |
| 1087 | FormatTok->Type = TT_ImplicitStringLiteral; |
| 1088 | break; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1089 | default: |
Daniel Jasper | 1d82b1a | 2013-10-11 19:45:02 +0000 | [diff] [blame] | 1090 | FormatTok->Type = TT_ImplicitStringLiteral; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1091 | ++Column; |
| 1092 | break; |
| 1093 | } |
| 1094 | } |
| 1095 | |
Daniel Jasper | 1d82b1a | 2013-10-11 19:45:02 +0000 | [diff] [blame] | 1096 | if (FormatTok->Type == TT_ImplicitStringLiteral) |
| 1097 | break; |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1098 | WhitespaceLength += FormatTok->Tok.getLength(); |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1099 | |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1100 | readRawToken(*FormatTok); |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1101 | } |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1102 | |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1103 | // In case the token starts with escaped newlines, we want to |
| 1104 | // take them into account as whitespace - this pattern is quite frequent |
| 1105 | // in macro definitions. |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1106 | // FIXME: Add a more explicit test. |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1107 | while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' && |
| 1108 | FormatTok->TokenText[1] == '\n') { |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1109 | // FIXME: ++FormatTok->NewlinesBefore is missing... |
Manuel Klimek | ad3094b | 2013-05-23 10:56:37 +0000 | [diff] [blame] | 1110 | WhitespaceLength += 2; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1111 | Column = 0; |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1112 | FormatTok->TokenText = FormatTok->TokenText.substr(2); |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1113 | } |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1114 | |
| 1115 | FormatTok->WhitespaceRange = SourceRange( |
| 1116 | WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); |
| 1117 | |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1118 | FormatTok->OriginalColumn = Column; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1119 | |
Alexander Kornienko | 54e6c9d | 2013-06-07 17:45:07 +0000 | [diff] [blame] | 1120 | TrailingWhitespace = 0; |
| 1121 | if (FormatTok->Tok.is(tok::comment)) { |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1122 | // FIXME: Add the trimmed whitespace to Column. |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1123 | StringRef UntrimmedText = FormatTok->TokenText; |
Alexander Kornienko | 51bb5d9 | 2013-09-06 17:24:54 +0000 | [diff] [blame] | 1124 | FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1125 | TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); |
Alexander Kornienko | 54e6c9d | 2013-06-07 17:45:07 +0000 | [diff] [blame] | 1126 | } else if (FormatTok->Tok.is(tok::raw_identifier)) { |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1127 | IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1128 | FormatTok->Tok.setIdentifierInfo(&Info); |
| 1129 | FormatTok->Tok.setKind(Info.getTokenID()); |
Alexander Kornienko | 54e6c9d | 2013-06-07 17:45:07 +0000 | [diff] [blame] | 1130 | } else if (FormatTok->Tok.is(tok::greatergreater)) { |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1131 | FormatTok->Tok.setKind(tok::greater); |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1132 | FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1133 | GreaterStashed = true; |
| 1134 | } |
| 1135 | |
Alexander Kornienko | 54e6c9d | 2013-06-07 17:45:07 +0000 | [diff] [blame] | 1136 | // Now FormatTok is the next non-whitespace token. |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 1137 | |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1138 | StringRef Text = FormatTok->TokenText; |
| 1139 | size_t FirstNewlinePos = Text.find('\n'); |
Alexander Kornienko | 6f6154c | 2013-09-10 12:29:48 +0000 | [diff] [blame] | 1140 | if (FirstNewlinePos == StringRef::npos) { |
| 1141 | // FIXME: ColumnWidth actually depends on the start column, we need to |
| 1142 | // take this into account when the token is moved. |
| 1143 | FormatTok->ColumnWidth = |
| 1144 | encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); |
| 1145 | Column += FormatTok->ColumnWidth; |
| 1146 | } else { |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1147 | FormatTok->IsMultiline = true; |
Alexander Kornienko | 6f6154c | 2013-09-10 12:29:48 +0000 | [diff] [blame] | 1148 | // FIXME: ColumnWidth actually depends on the start column, we need to |
| 1149 | // take this into account when the token is moved. |
| 1150 | FormatTok->ColumnWidth = encoding::columnWidthWithTabs( |
| 1151 | Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); |
| 1152 | |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1153 | // The last line of the token always starts in column 0. |
| 1154 | // Thus, the length can be precomputed even in the presence of tabs. |
| 1155 | FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( |
| 1156 | Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, |
| 1157 | Encoding); |
Alexander Kornienko | 6f6154c | 2013-09-10 12:29:48 +0000 | [diff] [blame] | 1158 | Column = FormatTok->LastLineColumnWidth; |
Alexander Kornienko | 4b762a9 | 2013-09-02 13:58:14 +0000 | [diff] [blame] | 1159 | } |
Alexander Kornienko | 83a7dcd | 2013-09-10 09:38:25 +0000 | [diff] [blame] | 1160 | |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1161 | return FormatTok; |
| 1162 | } |
| 1163 | |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1164 | FormatToken *FormatTok; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1165 | bool GreaterStashed; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1166 | unsigned Column; |
Manuel Klimek | de008c0 | 2013-05-27 15:23:34 +0000 | [diff] [blame] | 1167 | unsigned TrailingWhitespace; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1168 | Lexer &Lex; |
| 1169 | SourceManager &SourceMgr; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1170 | FormatStyle &Style; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1171 | IdentifierTable IdentTable; |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 1172 | encoding::Encoding Encoding; |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1173 | llvm::SpecificBumpPtrAllocator<FormatToken> Allocator; |
| 1174 | SmallVector<FormatToken *, 16> Tokens; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1175 | |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1176 | void readRawToken(FormatToken &Tok) { |
| 1177 | Lex.LexFromRawLexer(Tok.Tok); |
| 1178 | Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), |
| 1179 | Tok.Tok.getLength()); |
Daniel Jasper | 561211d | 2013-07-16 20:28:33 +0000 | [diff] [blame] | 1180 | // For formatting, treat unterminated string literals like normal string |
| 1181 | // literals. |
| 1182 | if (Tok.is(tok::unknown) && !Tok.TokenText.empty() && |
| 1183 | Tok.TokenText[0] == '"') { |
| 1184 | Tok.Tok.setKind(tok::string_literal); |
| 1185 | Tok.IsUnterminatedLiteral = true; |
| 1186 | } |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1187 | } |
| 1188 | }; |
| 1189 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1190 | class Formatter : public UnwrappedLineConsumer { |
| 1191 | public: |
Daniel Jasper | caf42a3 | 2013-05-15 08:14:19 +0000 | [diff] [blame] | 1192 | Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr, |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1193 | const std::vector<CharSourceRange> &Ranges) |
Daniel Jasper | caf42a3 | 2013-05-15 08:14:19 +0000 | [diff] [blame] | 1194 | : Style(Style), Lex(Lex), SourceMgr(SourceMgr), |
Alexander Kornienko | 73d845c | 2013-09-11 12:25:57 +0000 | [diff] [blame] | 1195 | Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())), |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 1196 | Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1), |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1197 | Encoding(encoding::detectEncoding(Lex.getBuffer())) { |
Daniel Jasper | 9637dda | 2013-07-15 14:33:14 +0000 | [diff] [blame] | 1198 | DEBUG(llvm::dbgs() << "File encoding: " |
| 1199 | << (Encoding == encoding::Encoding_UTF8 ? "UTF8" |
| 1200 | : "unknown") |
| 1201 | << "\n"); |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 1202 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1203 | |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1204 | tooling::Replacements format() { |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1205 | tooling::Replacements Result; |
Manuel Klimek | c41e819 | 2013-08-29 15:21:40 +0000 | [diff] [blame] | 1206 | FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding); |
Manuel Klimek | 96e888b | 2013-05-28 11:55:06 +0000 | [diff] [blame] | 1207 | |
| 1208 | UnwrappedLineParser Parser(Style, Tokens.lex(), *this); |
Manuel Klimek | 67d080d | 2013-04-12 14:13:36 +0000 | [diff] [blame] | 1209 | bool StructuralError = Parser.parse(); |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1210 | assert(UnwrappedLines.rbegin()->empty()); |
| 1211 | for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; |
| 1212 | ++Run) { |
| 1213 | DEBUG(llvm::dbgs() << "Run " << Run << "...\n"); |
| 1214 | SmallVector<AnnotatedLine *, 16> AnnotatedLines; |
| 1215 | for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) { |
| 1216 | AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i])); |
| 1217 | } |
| 1218 | tooling::Replacements RunResult = |
| 1219 | format(AnnotatedLines, StructuralError, Tokens); |
| 1220 | DEBUG({ |
| 1221 | llvm::dbgs() << "Replacements for run " << Run << ":\n"; |
| 1222 | for (tooling::Replacements::iterator I = RunResult.begin(), |
| 1223 | E = RunResult.end(); |
| 1224 | I != E; ++I) { |
| 1225 | llvm::dbgs() << I->toString() << "\n"; |
| 1226 | } |
| 1227 | }); |
| 1228 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
| 1229 | delete AnnotatedLines[i]; |
| 1230 | } |
| 1231 | Result.insert(RunResult.begin(), RunResult.end()); |
| 1232 | Whitespaces.reset(); |
| 1233 | } |
| 1234 | return Result; |
| 1235 | } |
| 1236 | |
| 1237 | tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines, |
| 1238 | bool StructuralError, FormatTokenLexer &Tokens) { |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 1239 | TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in")); |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1240 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 1241 | Annotator.annotate(*AnnotatedLines[i]); |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1242 | } |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1243 | deriveLocalStyle(AnnotatedLines); |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1244 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 1245 | Annotator.calculateFormattingInformation(*AnnotatedLines[i]); |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1246 | } |
Daniel Jasper | 5999f76 | 2013-04-09 17:46:55 +0000 | [diff] [blame] | 1247 | |
Daniel Jasper | b77d741 | 2013-09-06 07:54:20 +0000 | [diff] [blame] | 1248 | Annotator.setCommentLineLevels(AnnotatedLines); |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 1249 | ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding, |
| 1250 | BinPackInconclusiveFunctions); |
| 1251 | UnwrappedLineFormatter Formatter(SourceMgr, Ranges, &Indenter, &Whitespaces, |
| 1252 | Style); |
| 1253 | Formatter.format(AnnotatedLines, /*DryRun=*/false); |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1254 | return Whitespaces.generateReplacements(); |
| 1255 | } |
| 1256 | |
| 1257 | private: |
Alexander Kornienko | 73d845c | 2013-09-11 12:25:57 +0000 | [diff] [blame] | 1258 | static bool inputUsesCRLF(StringRef Text) { |
| 1259 | return Text.count('\r') * 2 > Text.count('\n'); |
| 1260 | } |
| 1261 | |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1262 | void |
| 1263 | deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1264 | unsigned CountBoundToVariable = 0; |
| 1265 | unsigned CountBoundToType = 0; |
| 1266 | bool HasCpp03IncompatibleFormat = false; |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 1267 | bool HasBinPackedFunction = false; |
| 1268 | bool HasOnePerLineFunction = false; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1269 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 1270 | if (!AnnotatedLines[i]->First->Next) |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1271 | continue; |
Daniel Jasper | 567dcf9 | 2013-09-05 09:29:45 +0000 | [diff] [blame] | 1272 | FormatToken *Tok = AnnotatedLines[i]->First->Next; |
Manuel Klimek | b398701 | 2013-05-29 14:47:47 +0000 | [diff] [blame] | 1273 | while (Tok->Next) { |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1274 | if (Tok->Type == TT_PointerOrReference) { |
Manuel Klimek | b398701 | 2013-05-29 14:47:47 +0000 | [diff] [blame] | 1275 | bool SpacesBefore = |
| 1276 | Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd(); |
| 1277 | bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() != |
| 1278 | Tok->Next->WhitespaceRange.getEnd(); |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1279 | if (SpacesBefore && !SpacesAfter) |
| 1280 | ++CountBoundToVariable; |
| 1281 | else if (!SpacesBefore && SpacesAfter) |
| 1282 | ++CountBoundToType; |
| 1283 | } |
| 1284 | |
Daniel Jasper | 78a4e61 | 2013-10-12 05:16:06 +0000 | [diff] [blame] | 1285 | if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) { |
| 1286 | if (Tok->is(tok::coloncolon) && |
| 1287 | Tok->Previous->Type == TT_TemplateOpener) |
| 1288 | HasCpp03IncompatibleFormat = true; |
| 1289 | if (Tok->Type == TT_TemplateCloser && |
| 1290 | Tok->Previous->Type == TT_TemplateCloser) |
| 1291 | HasCpp03IncompatibleFormat = true; |
| 1292 | } |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 1293 | |
| 1294 | if (Tok->PackingKind == PPK_BinPacked) |
| 1295 | HasBinPackedFunction = true; |
| 1296 | if (Tok->PackingKind == PPK_OnePerLine) |
| 1297 | HasOnePerLineFunction = true; |
| 1298 | |
Manuel Klimek | b398701 | 2013-05-29 14:47:47 +0000 | [diff] [blame] | 1299 | Tok = Tok->Next; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1300 | } |
| 1301 | } |
| 1302 | if (Style.DerivePointerBinding) { |
| 1303 | if (CountBoundToType > CountBoundToVariable) |
| 1304 | Style.PointerBindsToType = true; |
| 1305 | else if (CountBoundToType < CountBoundToVariable) |
| 1306 | Style.PointerBindsToType = false; |
| 1307 | } |
| 1308 | if (Style.Standard == FormatStyle::LS_Auto) { |
| 1309 | Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11 |
| 1310 | : FormatStyle::LS_Cpp03; |
| 1311 | } |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 1312 | BinPackInconclusiveFunctions = |
| 1313 | HasBinPackedFunction || !HasOnePerLineFunction; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1314 | } |
| 1315 | |
Manuel Klimek | f9ea2ed | 2013-01-10 19:49:59 +0000 | [diff] [blame] | 1316 | virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) { |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1317 | assert(!UnwrappedLines.empty()); |
| 1318 | UnwrappedLines.back().push_back(TheLine); |
| 1319 | } |
| 1320 | |
| 1321 | virtual void finishRun() { |
| 1322 | UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>()); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1323 | } |
| 1324 | |
| 1325 | FormatStyle Style; |
| 1326 | Lexer &Lex; |
| 1327 | SourceManager &SourceMgr; |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 1328 | WhitespaceManager Whitespaces; |
Daniel Jasper | 2a80ad6 | 2013-11-05 19:10:03 +0000 | [diff] [blame^] | 1329 | SmallVector<CharSourceRange, 8> Ranges; |
Manuel Klimek | ae76f7f | 2013-10-11 21:25:45 +0000 | [diff] [blame] | 1330 | SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines; |
Alexander Kornienko | 0089510 | 2013-06-05 14:09:10 +0000 | [diff] [blame] | 1331 | |
| 1332 | encoding::Encoding Encoding; |
Daniel Jasper | c7bd68f | 2013-07-10 14:02:49 +0000 | [diff] [blame] | 1333 | bool BinPackInconclusiveFunctions; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1334 | }; |
| 1335 | |
Craig Topper | 83f81d7 | 2013-06-30 22:29:28 +0000 | [diff] [blame] | 1336 | } // end anonymous namespace |
| 1337 | |
Alexander Kornienko | 70ce788 | 2013-04-15 14:28:00 +0000 | [diff] [blame] | 1338 | tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex, |
| 1339 | SourceManager &SourceMgr, |
Daniel Jasper | caf42a3 | 2013-05-15 08:14:19 +0000 | [diff] [blame] | 1340 | std::vector<CharSourceRange> Ranges) { |
| 1341 | Formatter formatter(Style, Lex, SourceMgr, Ranges); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1342 | return formatter.format(); |
| 1343 | } |
| 1344 | |
Daniel Jasper | 8a99945 | 2013-05-16 10:40:07 +0000 | [diff] [blame] | 1345 | tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, |
| 1346 | std::vector<tooling::Range> Ranges, |
| 1347 | StringRef FileName) { |
| 1348 | FileManager Files((FileSystemOptions())); |
| 1349 | DiagnosticsEngine Diagnostics( |
| 1350 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
| 1351 | new DiagnosticOptions); |
| 1352 | SourceManager SourceMgr(Diagnostics, Files); |
| 1353 | llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName); |
| 1354 | const clang::FileEntry *Entry = |
| 1355 | Files.getVirtualFile(FileName, Buf->getBufferSize(), 0); |
| 1356 | SourceMgr.overrideFileContents(Entry, Buf); |
| 1357 | FileID ID = |
| 1358 | SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User); |
Alexander Kornienko | a1753f4 | 2013-06-28 12:51:24 +0000 | [diff] [blame] | 1359 | Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, |
| 1360 | getFormattingLangOpts(Style.Standard)); |
Daniel Jasper | 8a99945 | 2013-05-16 10:40:07 +0000 | [diff] [blame] | 1361 | SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID); |
| 1362 | std::vector<CharSourceRange> CharRanges; |
| 1363 | for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { |
| 1364 | SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset()); |
| 1365 | SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength()); |
| 1366 | CharRanges.push_back(CharSourceRange::getCharRange(Start, End)); |
| 1367 | } |
| 1368 | return reformat(Style, Lex, SourceMgr, CharRanges); |
| 1369 | } |
| 1370 | |
Alexander Kornienko | a1753f4 | 2013-06-28 12:51:24 +0000 | [diff] [blame] | 1371 | LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) { |
Daniel Jasper | 46ef852 | 2013-01-10 13:08:12 +0000 | [diff] [blame] | 1372 | LangOptions LangOpts; |
| 1373 | LangOpts.CPlusPlus = 1; |
Alexander Kornienko | a1753f4 | 2013-06-28 12:51:24 +0000 | [diff] [blame] | 1374 | LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1; |
Daniel Jasper | b64eca0 | 2013-03-22 10:01:29 +0000 | [diff] [blame] | 1375 | LangOpts.LineComment = 1; |
Daniel Jasper | 46ef852 | 2013-01-10 13:08:12 +0000 | [diff] [blame] | 1376 | LangOpts.Bool = 1; |
| 1377 | LangOpts.ObjC1 = 1; |
| 1378 | LangOpts.ObjC2 = 1; |
| 1379 | return LangOpts; |
| 1380 | } |
| 1381 | |
Edwin Vane | f4e12c8 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 1382 | const char *StyleOptionHelpDescription = |
| 1383 | "Coding style, currently supports:\n" |
| 1384 | " LLVM, Google, Chromium, Mozilla, WebKit.\n" |
| 1385 | "Use -style=file to load style configuration from\n" |
| 1386 | ".clang-format file located in one of the parent\n" |
| 1387 | "directories of the source file (or current\n" |
| 1388 | "directory for stdin).\n" |
| 1389 | "Use -style=\"{key: value, ...}\" to set specific\n" |
| 1390 | "parameters, e.g.:\n" |
| 1391 | " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; |
| 1392 | |
| 1393 | FormatStyle getStyle(StringRef StyleName, StringRef FileName) { |
| 1394 | // Fallback style in case the rest of this function can't determine a style. |
| 1395 | StringRef FallbackStyle = "LLVM"; |
| 1396 | FormatStyle Style; |
| 1397 | getPredefinedStyle(FallbackStyle, &Style); |
| 1398 | |
| 1399 | if (StyleName.startswith("{")) { |
| 1400 | // Parse YAML/JSON style from the command line. |
| 1401 | if (llvm::error_code ec = parseConfiguration(StyleName, &Style)) { |
Alexander Kornienko | f0fc89c | 2013-10-14 00:46:35 +0000 | [diff] [blame] | 1402 | llvm::errs() << "Error parsing -style: " << ec.message() << ", using " |
| 1403 | << FallbackStyle << " style\n"; |
Edwin Vane | f4e12c8 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 1404 | } |
| 1405 | return Style; |
| 1406 | } |
| 1407 | |
| 1408 | if (!StyleName.equals_lower("file")) { |
| 1409 | if (!getPredefinedStyle(StyleName, &Style)) |
| 1410 | llvm::errs() << "Invalid value for -style, using " << FallbackStyle |
| 1411 | << " style\n"; |
| 1412 | return Style; |
| 1413 | } |
| 1414 | |
| 1415 | SmallString<128> Path(FileName); |
| 1416 | llvm::sys::fs::make_absolute(Path); |
Alexander Kornienko | f0fc89c | 2013-10-14 00:46:35 +0000 | [diff] [blame] | 1417 | for (StringRef Directory = Path; !Directory.empty(); |
Edwin Vane | f4e12c8 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 1418 | Directory = llvm::sys::path::parent_path(Directory)) { |
| 1419 | if (!llvm::sys::fs::is_directory(Directory)) |
| 1420 | continue; |
| 1421 | SmallString<128> ConfigFile(Directory); |
| 1422 | |
| 1423 | llvm::sys::path::append(ConfigFile, ".clang-format"); |
| 1424 | DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); |
| 1425 | bool IsFile = false; |
| 1426 | // Ignore errors from is_regular_file: we only need to know if we can read |
| 1427 | // the file or not. |
| 1428 | llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile); |
| 1429 | |
| 1430 | if (!IsFile) { |
| 1431 | // Try _clang-format too, since dotfiles are not commonly used on Windows. |
| 1432 | ConfigFile = Directory; |
| 1433 | llvm::sys::path::append(ConfigFile, "_clang-format"); |
| 1434 | DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); |
| 1435 | llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile); |
| 1436 | } |
| 1437 | |
| 1438 | if (IsFile) { |
| 1439 | OwningPtr<llvm::MemoryBuffer> Text; |
Rafael Espindola | 28ce23a | 2013-10-25 19:00:49 +0000 | [diff] [blame] | 1440 | if (llvm::error_code ec = |
| 1441 | llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) { |
Edwin Vane | f4e12c8 | 2013-09-30 13:31:48 +0000 | [diff] [blame] | 1442 | llvm::errs() << ec.message() << "\n"; |
| 1443 | continue; |
| 1444 | } |
| 1445 | if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) { |
| 1446 | llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message() |
| 1447 | << "\n"; |
| 1448 | continue; |
| 1449 | } |
| 1450 | DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); |
| 1451 | return Style; |
| 1452 | } |
| 1453 | } |
| 1454 | llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle |
| 1455 | << " style\n"; |
| 1456 | return Style; |
| 1457 | } |
| 1458 | |
Daniel Jasper | cd16238 | 2013-01-07 13:26:07 +0000 | [diff] [blame] | 1459 | } // namespace format |
| 1460 | } // namespace clang |