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