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