blob: 39d2c0f96c3667ed6443bd2c6eed54fae4c7f2b9 [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- 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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper6b2afe42013-08-16 11:20:30 +000018#include "ContinuationIndenter.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasper8a999452013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000024#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000029#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000030#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000031#include <string>
32
Alexander Kornienkod71ec162013-05-07 15:32:14 +000033namespace llvm {
34namespace yaml {
35template <>
36struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000037 static void enumeration(IO &IO,
38 clang::format::FormatStyle::LanguageStandard &Value) {
39 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
40 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
41 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
42 }
43};
44
Daniel Jasper1fb8d882013-05-14 09:30:02 +000045template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000046struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
47 static void
48 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
49 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
50 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
51 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
Manuel Klimeke4907052013-08-02 21:31:59 +000052 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000053 }
54};
55
Daniel Jaspereff18b92013-07-31 23:16:02 +000056template <>
57struct ScalarEnumerationTraits<
58 clang::format::FormatStyle::NamespaceIndentationKind> {
59 static void
60 enumeration(IO &IO,
61 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
62 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
63 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
64 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
65 }
66};
67
Alexander Kornienkod71ec162013-05-07 15:32:14 +000068template <> struct MappingTraits<clang::format::FormatStyle> {
69 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000070 if (IO.outputting()) {
71 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
72 ArrayRef<StringRef> Styles(StylesArray);
73 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
74 StringRef StyleName(Styles[i]);
Alexander Kornienko885f87b2013-05-19 00:53:30 +000075 clang::format::FormatStyle PredefinedStyle;
76 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
77 Style == PredefinedStyle) {
Alexander Kornienkodd256312013-05-10 11:56:10 +000078 IO.mapOptional("# BasedOnStyle", StyleName);
79 break;
80 }
81 }
82 } else {
Alexander Kornienkod71ec162013-05-07 15:32:14 +000083 StringRef BasedOnStyle;
84 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000085 if (!BasedOnStyle.empty())
Alexander Kornienko885f87b2013-05-19 00:53:30 +000086 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
87 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
88 return;
89 }
Alexander Kornienkod71ec162013-05-07 15:32:14 +000090 }
91
92 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jasper6315fec2013-08-13 10:58:30 +000093 IO.mapOptional("ConstructorInitializerIndentWidth",
94 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000095 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +000096 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000097 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
98 Style.AllowAllParametersOfDeclarationOnNextLine);
99 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
100 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000101 IO.mapOptional("AllowShortLoopsOnASingleLine",
102 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000103 IO.mapOptional("AlwaysBreakTemplateDeclarations",
104 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000105 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
106 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000107 IO.mapOptional("BreakBeforeBinaryOperators",
108 Style.BreakBeforeBinaryOperators);
109 IO.mapOptional("BreakConstructorInitializersBeforeComma",
110 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000111 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
112 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
113 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
114 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
115 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000116 IO.mapOptional("ExperimentalAutoDetectBinPacking",
117 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000118 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
119 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000120 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000121 IO.mapOptional("ObjCSpaceBeforeProtocolList",
122 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000123 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
124 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000125 IO.mapOptional("PenaltyBreakFirstLessLess",
126 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000127 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
128 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
129 Style.PenaltyReturnTypeOnItsOwnLine);
130 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
131 IO.mapOptional("SpacesBeforeTrailingComments",
132 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000133 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000134 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000135 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000136 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000137 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000138 IO.mapOptional("IndentFunctionDeclarationAfterType",
139 Style.IndentFunctionDeclarationAfterType);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000140 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
Daniel Jasper34f3d052013-08-21 08:39:01 +0000141 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000142 IO.mapOptional("SpacesInCStyleCastParentheses",
143 Style.SpacesInCStyleCastParentheses);
144 IO.mapOptional("SpaceAfterControlStatementKeyword",
145 Style.SpaceAfterControlStatementKeyword);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000146 }
147};
148}
149}
150
Daniel Jasperbac016b2012-12-03 18:12:45 +0000151namespace clang {
152namespace format {
153
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000154void setDefaultPenalties(FormatStyle &Style) {
Daniel Jasperf5461782013-08-28 10:03:58 +0000155 Style.PenaltyBreakComment = 60;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000156 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000157 Style.PenaltyBreakString = 1000;
158 Style.PenaltyExcessCharacter = 1000000;
159}
160
Daniel Jasperbac016b2012-12-03 18:12:45 +0000161FormatStyle getLLVMStyle() {
162 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000163 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000164 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000165 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000166 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000167 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000168 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000169 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000170 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000171 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000172 LLVMStyle.BreakBeforeBinaryOperators = false;
173 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
174 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000175 LLVMStyle.ColumnLimit = 80;
176 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000177 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000178 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000179 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000180 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000181 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000182 LLVMStyle.IndentFunctionDeclarationAfterType = false;
183 LLVMStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000184 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000185 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000186 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000187 LLVMStyle.PointerBindsToType = false;
188 LLVMStyle.SpacesBeforeTrailingComments = 1;
189 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000190 LLVMStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000191 LLVMStyle.SpacesInParentheses = false;
192 LLVMStyle.SpaceInEmptyParentheses = false;
193 LLVMStyle.SpacesInCStyleCastParentheses = false;
194 LLVMStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000195
196 setDefaultPenalties(LLVMStyle);
197 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
198
Daniel Jasperbac016b2012-12-03 18:12:45 +0000199 return LLVMStyle;
200}
201
202FormatStyle getGoogleStyle() {
203 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000204 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000205 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000206 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000207 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000208 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000209 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000210 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000211 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000212 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000213 GoogleStyle.BreakBeforeBinaryOperators = false;
214 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
215 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000216 GoogleStyle.ColumnLimit = 80;
217 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper6315fec2013-08-13 10:58:30 +0000218 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000219 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000220 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000221 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000222 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000223 GoogleStyle.IndentFunctionDeclarationAfterType = true;
224 GoogleStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000225 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000226 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000227 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000228 GoogleStyle.PointerBindsToType = true;
229 GoogleStyle.SpacesBeforeTrailingComments = 2;
230 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000231 GoogleStyle.UseTab = false;
Daniel Jasper7df56bf2013-08-20 12:36:34 +0000232 GoogleStyle.SpacesInParentheses = false;
233 GoogleStyle.SpaceInEmptyParentheses = false;
234 GoogleStyle.SpacesInCStyleCastParentheses = false;
235 GoogleStyle.SpaceAfterControlStatementKeyword = true;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000236
237 setDefaultPenalties(GoogleStyle);
238 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
239
Daniel Jasperbac016b2012-12-03 18:12:45 +0000240 return GoogleStyle;
241}
242
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000243FormatStyle getChromiumStyle() {
244 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000245 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000246 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000247 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000248 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000249 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000250 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000251 return ChromiumStyle;
252}
253
Alexander Kornienkofb594862013-05-06 14:11:27 +0000254FormatStyle getMozillaStyle() {
255 FormatStyle MozillaStyle = getLLVMStyle();
256 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
257 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
258 MozillaStyle.DerivePointerBinding = true;
259 MozillaStyle.IndentCaseLabels = true;
260 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
261 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
262 MozillaStyle.PointerBindsToType = true;
263 return MozillaStyle;
264}
265
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000266FormatStyle getWebKitStyle() {
267 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000268 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000269 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000270 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000271 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000272 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000273 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000274 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000275 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000276 Style.PointerBindsToType = true;
277 return Style;
278}
279
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000280bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000281 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000282 *Style = getLLVMStyle();
283 else if (Name.equals_lower("chromium"))
284 *Style = getChromiumStyle();
285 else if (Name.equals_lower("mozilla"))
286 *Style = getMozillaStyle();
287 else if (Name.equals_lower("google"))
288 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000289 else if (Name.equals_lower("webkit"))
290 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000291 else
292 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000293
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000294 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000295}
296
297llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000298 if (Text.trim().empty())
299 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000300 llvm::yaml::Input Input(Text);
301 Input >> *Style;
302 return Input.error();
303}
304
305std::string configurationAsText(const FormatStyle &Style) {
306 std::string Text;
307 llvm::raw_string_ostream Stream(Text);
308 llvm::yaml::Output Output(Stream);
309 // We use the same mapping method for input and output, so we need a non-const
310 // reference here.
311 FormatStyle NonConstStyle = Style;
312 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000313 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000314}
315
Craig Topper83f81d72013-06-30 22:29:28 +0000316namespace {
317
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000318class NoColumnLimitFormatter {
319public:
Daniel Jasper34f3d052013-08-21 08:39:01 +0000320 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000321
322 /// \brief Formats the line starting at \p State, simply keeping all of the
323 /// input's line breaking decisions.
324 void format() {
325 LineState State = Indenter->getInitialState();
326 while (State.NextToken != NULL) {
327 bool Newline =
328 Indenter->mustBreak(State) ||
329 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
330 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
331 }
332 }
Daniel Jasper34f3d052013-08-21 08:39:01 +0000333
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000334private:
335 ContinuationIndenter *Indenter;
336};
337
Daniel Jasperbac016b2012-12-03 18:12:45 +0000338class UnwrappedLineFormatter {
339public:
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000340 UnwrappedLineFormatter(ContinuationIndenter *Indenter,
341 const FormatStyle &Style, const AnnotatedLine &Line)
342 : Indenter(Indenter), Style(Style), Line(Line), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000343
Manuel Klimekd4397b92013-01-04 23:34:14 +0000344 /// \brief Formats an \c UnwrappedLine.
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000345 void format() {
346 LineState State = Indenter->getInitialState();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000347
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000348 // If the ObjC method declaration does not fit on a line, we should format
349 // it with one arg per line.
350 if (Line.Type == LT_ObjCMethodDecl)
351 State.Stack.back().BreakBeforeParameter = true;
352
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000353 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000354 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000355 }
356
357private:
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000358 /// \brief An edge in the solution space from \c Previous->State to \c State,
359 /// inserting a newline dependent on the \c NewLine.
360 struct StateNode {
361 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000362 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000363 LineState State;
364 bool NewLine;
365 StateNode *Previous;
366 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000367
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000368 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
369 ///
370 /// In case of equal penalties, we want to prefer states that were inserted
371 /// first. During state generation we make sure that we insert states first
372 /// that break the line as late as possible.
373 typedef std::pair<unsigned, unsigned> OrderedPenalty;
374
375 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
376 /// \c State has the given \c OrderedPenalty.
377 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
378
379 /// \brief The BFS queue type.
380 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
381 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000382
383 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000384 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000385 /// This implements a variant of Dijkstra's algorithm on the graph that spans
386 /// the solution space (\c LineStates are the nodes). The algorithm tries to
387 /// find the shortest path (the one with lowest penalty) from \p InitialState
388 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000389 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000390 std::set<LineState> Seen;
391
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000392 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000393 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000394 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
395 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
396 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000397
398 // While not empty, take first element and follow edges.
399 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000400 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000401 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000402 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +0000403 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000404 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000405 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000406 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000407
Daniel Jasper54b4e442013-05-22 05:27:42 +0000408 // Cut off the analysis of certain solutions if the analysis gets too
409 // complex. See description of IgnoreStackForComparison.
410 if (Count > 10000)
411 Node->State.IgnoreStackForComparison = true;
412
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000413 if (!Seen.insert(Node->State).second)
414 // State already examined with lower penalty.
415 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000416
Nico Weber27268772013-06-26 00:30:14 +0000417 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
418 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000419 }
420
421 if (Queue.empty())
422 // We were unable to find a solution, do nothing.
423 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000424 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000426 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000427 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +0000428 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
429 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000430 }
431
432 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +0000433 std::deque<StateNode *> Path;
434 // We do not need a break before the initial token.
435 while (Current->Previous) {
436 Path.push_front(Current);
437 Current = Current->Previous;
438 }
439 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
440 I != E; ++I) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000441 unsigned Penalty = Indenter->addTokenToState(State, (*I)->NewLine, false);
Daniel Jasper259118e2013-08-22 16:11:46 +0000442 (void)Penalty;
Manuel Klimek9c333b92013-05-29 15:10:11 +0000443 DEBUG({
444 if ((*I)->NewLine) {
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000445 llvm::dbgs() << "Penalty for placing "
Manuel Klimek9c333b92013-05-29 15:10:11 +0000446 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
Daniel Jasperd4a03db2013-08-22 15:00:41 +0000447 << Penalty << "\n";
Manuel Klimek9c333b92013-05-29 15:10:11 +0000448 }
449 });
Manuel Klimek9c333b92013-05-29 15:10:11 +0000450 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000451 }
452
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000453 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000454 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000455 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000456 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000457 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
458 bool NewLine) {
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000459 if (NewLine && !Indenter->canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000460 return;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000461 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000462 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000463
464 StateNode *Node = new (Allocator.Allocate())
465 StateNode(PreviousNode->State, NewLine, PreviousNode);
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000466 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
467 if (Node->State.Column > Indenter->getColumnLimit()) {
468 unsigned ExcessCharacters =
469 Node->State.Column - Indenter->getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000470 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000471 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000472
473 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
474 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000475 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000476
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000477 ContinuationIndenter *Indenter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000478 FormatStyle Style;
Daniel Jasper995e8202013-01-14 13:08:07 +0000479 const AnnotatedLine &Line;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000480
481 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
482 QueueType Queue;
483 // Increasing count of \c StateNode items we have created. This is used
484 // to create a deterministic order independent of the container.
485 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000486};
487
Manuel Klimek96e888b2013-05-28 11:55:06 +0000488class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000489public:
Manuel Klimekc41e8192013-08-29 15:21:40 +0000490 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
Alexander Kornienko00895102013-06-05 14:09:10 +0000491 encoding::Encoding Encoding)
Manuel Klimekc41e8192013-08-29 15:21:40 +0000492 : FormatTok(NULL), GreaterStashed(false), Column(0),
493 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style),
494 IdentTable(getFormattingLangOpts()), Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000495 Lex.SetKeepWhitespaceMode(true);
496 }
497
Manuel Klimek96e888b2013-05-28 11:55:06 +0000498 ArrayRef<FormatToken *> lex() {
499 assert(Tokens.empty());
500 do {
501 Tokens.push_back(getNextToken());
502 } while (Tokens.back()->Tok.isNot(tok::eof));
503 return Tokens;
504 }
505
506 IdentifierTable &getIdentTable() { return IdentTable; }
507
508private:
509 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000510 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000511 // Create a synthesized second '>' token.
Manuel Klimekc41e8192013-08-29 15:21:40 +0000512 // FIXME: Increment Column and set OriginalColumn.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000513 Token Greater = FormatTok->Tok;
514 FormatTok = new (Allocator.Allocate()) FormatToken;
515 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +0000516 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000517 FormatTok->Tok.getLocation().getLocWithOffset(1);
518 FormatTok->WhitespaceRange =
519 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000520 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +0000521 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000522 GreaterStashed = false;
523 return FormatTok;
524 }
525
Manuel Klimek96e888b2013-05-28 11:55:06 +0000526 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +0000527 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +0000528 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +0000529 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +0000530 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +0000531 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000532
533 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +0000534 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000535 while (FormatTok->Tok.is(tok::unknown)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000536 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
537 switch (FormatTok->TokenText[i]) {
538 case '\n':
539 ++FormatTok->NewlinesBefore;
540 // FIXME: This is technically incorrect, as it could also
541 // be a literal backslash at the end of the line.
542 if (i == 0 || FormatTok->TokenText[i-1] != '\\')
543 FormatTok->HasUnescapedNewline = true;
544 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
545 Column = 0;
546 break;
547 case ' ':
548 ++Column;
549 break;
550 case '\t':
551 Column += Style.IndentWidth - Column % Style.IndentWidth;
552 break;
553 default:
554 ++Column;
555 break;
556 }
557 }
558
Manuel Klimek96e888b2013-05-28 11:55:06 +0000559 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000560
Daniel Jasper561211d2013-07-16 20:28:33 +0000561 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000562 }
Manuel Klimek95419382013-01-07 07:56:50 +0000563
Manuel Klimekd4397b92013-01-04 23:34:14 +0000564 // In case the token starts with escaped newlines, we want to
565 // take them into account as whitespace - this pattern is quite frequent
566 // in macro definitions.
567 // FIXME: What do we want to do with other escaped spaces, and escaped
568 // spaces or newlines in the middle of tokens?
569 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +0000570 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
571 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000572 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +0000573 WhitespaceLength += 2;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000574 Column = 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000575 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000576 }
Manuel Klimekc41e8192013-08-29 15:21:40 +0000577 FormatTok->OriginalColumn = Column;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000578
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000579 TrailingWhitespace = 0;
580 if (FormatTok->Tok.is(tok::comment)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000581 // FIXME: Add the trimmed whitespace to Column.
Daniel Jasper561211d2013-07-16 20:28:33 +0000582 StringRef UntrimmedText = FormatTok->TokenText;
583 FormatTok->TokenText = FormatTok->TokenText.rtrim();
584 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000585 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +0000586 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000587 FormatTok->Tok.setIdentifierInfo(&Info);
588 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000589 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +0000590 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +0000591 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000592 GreaterStashed = true;
593 }
594
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +0000595 // Now FormatTok is the next non-whitespace token.
Daniel Jasper561211d2013-07-16 20:28:33 +0000596 FormatTok->CodePointCount =
597 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +0000598
Alexander Kornienko4b762a92013-09-02 13:58:14 +0000599 if (FormatTok->isOneOf(tok::string_literal, tok::comment)) {
600 StringRef Text = FormatTok->TokenText;
601 size_t FirstNewlinePos = Text.find('\n');
602 if (FirstNewlinePos != StringRef::npos) {
603 FormatTok->CodePointsInFirstLine = encoding::getCodePointCount(
604 Text.substr(0, FirstNewlinePos), Encoding);
605 FormatTok->CodePointsInLastLine = encoding::getCodePointCount(
606 Text.substr(Text.find_last_of('\n') + 1), Encoding);
607 }
608 }
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000609 // FIXME: Add the CodePointCount to Column.
Manuel Klimek96e888b2013-05-28 11:55:06 +0000610 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +0000611 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000612 return FormatTok;
613 }
614
Manuel Klimek96e888b2013-05-28 11:55:06 +0000615 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000616 bool GreaterStashed;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000617 unsigned Column;
Manuel Klimekde008c02013-05-27 15:23:34 +0000618 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000619 Lexer &Lex;
620 SourceManager &SourceMgr;
Manuel Klimekc41e8192013-08-29 15:21:40 +0000621 FormatStyle &Style;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000622 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +0000623 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +0000624 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
625 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000626
Daniel Jasper561211d2013-07-16 20:28:33 +0000627 void readRawToken(FormatToken &Tok) {
628 Lex.LexFromRawLexer(Tok.Tok);
629 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
630 Tok.Tok.getLength());
Daniel Jasper561211d2013-07-16 20:28:33 +0000631 // For formatting, treat unterminated string literals like normal string
632 // literals.
633 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
634 Tok.TokenText[0] == '"') {
635 Tok.Tok.setKind(tok::string_literal);
636 Tok.IsUnterminatedLiteral = true;
637 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000638 }
639};
640
Daniel Jasperbac016b2012-12-03 18:12:45 +0000641class Formatter : public UnwrappedLineConsumer {
642public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000643 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000644 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +0000645 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +0000646 Whitespaces(SourceMgr, Style), Ranges(Ranges),
647 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +0000648 DEBUG(llvm::dbgs() << "File encoding: "
649 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
650 : "unknown")
651 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +0000652 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000653
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000654 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000655
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000656 tooling::Replacements format() {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000657 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +0000658
659 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000660 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +0000661 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000662 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
663 Annotator.annotate(AnnotatedLines[i]);
664 }
665 deriveLocalStyle();
666 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
667 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
668 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000669
670 // Adapt level to the next line if this is a comment.
671 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000672 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +0000673 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000674 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000675 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000676 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +0000677 else
Daniel Jasper2a409b62013-07-08 14:34:09 +0000678 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
679 ? &AnnotatedLines[i]
680 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +0000681 }
682
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000683 std::vector<int> IndentForLevel;
684 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +0000685 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000686 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000687 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
688 E = AnnotatedLines.end();
689 I != E; ++I) {
690 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000691 const FormatToken *FirstTok = TheLine.First;
692 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000693
694 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000695 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000696 FormatPPDirective = false;
697 if (!FormatPPDirective && TheLine.InPPDirective &&
698 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
699 FormatPPDirective = true;
700
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000701 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000702 while (IndentForLevel.size() <= TheLine.Level)
703 IndentForLevel.push_back(-1);
704 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000705 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
706 if (static_cast<int>(Indent) + Offset >= 0)
707 Indent += Offset;
708 tryFitMultipleLinesInOne(Indent, I, E);
709
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000710 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000711 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000712 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000713 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +0000714 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000715 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000716 }
717 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +0000718 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000719 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000720 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +0000721 // Insert a break even if there is a structural error in case where
722 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000723 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000724 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000725 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000726 } else {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000727 Indent = LevelIndent = FirstTok->OriginalColumn;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000728 }
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000729 ContinuationIndenter Indenter(Style, SourceMgr, TheLine, Indent,
730 Whitespaces, Encoding,
731 BinPackInconclusiveFunctions);
732
733 // If everything fits on a single line, just put it there.
734 unsigned ColumnLimit = Style.ColumnLimit;
735 if ((I + 1) != E && (I + 1)->InPPDirective &&
736 !(I + 1)->First->HasUnescapedNewline)
737 ColumnLimit = Indenter.getColumnLimit();
738
739 if (I->Last->TotalLength + Indent <= ColumnLimit) {
740 LineState State = Indenter.getInitialState();
741 while (State.NextToken != NULL)
742 Indenter.addTokenToState(State, false, false);
743 } else if (Style.ColumnLimit == 0) {
744 NoColumnLimitFormatter Formatter(&Indenter);
745 Formatter.format();
746 } else {
747 UnwrappedLineFormatter Formatter(&Indenter, Style, TheLine);
748 Formatter.format();
749 }
750
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000751 IndentForLevel[TheLine.Level] = LevelIndent;
752 PreviousLineWasTouched = true;
753 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000754 // Format the first token if necessary, and notify the WhitespaceManager
755 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000756 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
757 Tok = Tok->Next) {
758 if (Tok == TheLine.First &&
759 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
Manuel Klimekc41e8192013-08-29 15:21:40 +0000760 unsigned LevelIndent = Tok->OriginalColumn;
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000761 // Remove trailing whitespace of the previous line if it was
762 // touched.
763 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
764 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
765 TheLine.InPPDirective);
766 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000767 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000768 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +0000769
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000770 if (static_cast<int>(LevelIndent) - Offset >= 0)
771 LevelIndent -= Offset;
772 if (Tok->isNot(tok::comment))
773 IndentForLevel[TheLine.Level] = LevelIndent;
774 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +0000775 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000776 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000777 }
778 // If we did not reformat this unwrapped line, the column at the end of
779 // the last token is unchanged - thus, we can calculate the end of the
780 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000781 PreviousLineWasTouched = false;
782 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000783 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000784 }
785 return Whitespaces.generateReplacements();
786 }
787
788private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000789 void deriveLocalStyle() {
790 unsigned CountBoundToVariable = 0;
791 unsigned CountBoundToType = 0;
792 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000793 bool HasBinPackedFunction = false;
794 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000795 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000796 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000797 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +0000798 FormatToken *Tok = AnnotatedLines[i].First->Next;
799 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000800 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000801 bool SpacesBefore =
802 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
803 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
804 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000805 if (SpacesBefore && !SpacesAfter)
806 ++CountBoundToVariable;
807 else if (!SpacesBefore && SpacesAfter)
808 ++CountBoundToType;
809 }
810
Daniel Jasper29f123b2013-02-08 15:28:42 +0000811 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000812 Tok->Previous->Type == TT_TemplateCloser &&
813 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000814 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000815
816 if (Tok->PackingKind == PPK_BinPacked)
817 HasBinPackedFunction = true;
818 if (Tok->PackingKind == PPK_OnePerLine)
819 HasOnePerLineFunction = true;
820
Manuel Klimekb3987012013-05-29 14:47:47 +0000821 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000822 }
823 }
824 if (Style.DerivePointerBinding) {
825 if (CountBoundToType > CountBoundToVariable)
826 Style.PointerBindsToType = true;
827 else if (CountBoundToType < CountBoundToVariable)
828 Style.PointerBindsToType = false;
829 }
830 if (Style.Standard == FormatStyle::LS_Auto) {
831 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
832 : FormatStyle::LS_Cpp03;
833 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000834 BinPackInconclusiveFunctions =
835 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000836 }
837
Manuel Klimek547d5db2013-02-08 17:38:27 +0000838 /// \brief Get the indent of \p Level from \p IndentForLevel.
839 ///
840 /// \p IndentForLevel must contain the indent for the level \c l
841 /// at \p IndentForLevel[l], or a value < 0 if the indent for
842 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +0000843 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +0000844 if (IndentForLevel[Level] != -1)
845 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +0000846 if (Level == 0)
847 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000848 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +0000849 }
850
851 /// \brief Get the offset of the line relatively to the level.
852 ///
853 /// For example, 'public:' labels in classes are offset by 1 or 2
854 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +0000855 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000856 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +0000857 return Style.AccessModifierOffset;
858 return 0;
859 }
860
Manuel Klimek517e8942013-01-11 17:54:10 +0000861 /// \brief Tries to merge lines into one.
862 ///
863 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
864 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000865 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +0000866 std::vector<AnnotatedLine>::iterator &I,
867 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000868 // We can never merge stuff if there are trailing line comments.
869 if (I->Last->Type == TT_LineComment)
870 return;
871
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000872 if (Indent > Style.ColumnLimit)
873 return;
874
Daniel Jaspera4d46212013-02-28 11:05:57 +0000875 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +0000876 // If we already exceed the column limit, we set 'Limit' to 0. The different
877 // tryMerge..() functions can then decide whether to still do merging.
878 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000879
Daniel Jasper9c8c40e2013-01-21 14:18:28 +0000880 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000881 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000882
Daniel Jasper5be59ba2013-05-15 14:09:55 +0000883 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000884 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000885 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000886 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000887 tryMergeSimpleControlStatement(I, E, Limit);
888 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000889 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000890 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +0000891 } else if (I->InPPDirective &&
892 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000893 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000894 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000895 }
896
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000897 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
898 std::vector<AnnotatedLine>::iterator E,
899 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000900 if (Limit == 0)
901 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000902 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000903 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +0000904 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000905 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000906 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000907 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000908 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000909 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000910 join(Line, *(++I));
911 }
912
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000913 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
914 std::vector<AnnotatedLine>::iterator E,
915 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000916 if (Limit == 0)
917 return;
Manuel Klimekd3a247c2013-08-07 19:20:45 +0000918 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
919 (I + 1)->First->is(tok::l_brace))
920 return;
Manuel Klimek4c128122013-01-18 14:46:43 +0000921 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000922 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +0000923 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000924 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000925 if (Line.Last->isNot(tok::r_paren))
926 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000927 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000928 return;
Manuel Klimekb3987012013-05-29 14:47:47 +0000929 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
930 tok::kw_while) ||
931 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000932 return;
933 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +0000934 if (I + 2 != E && Line.First->is(tok::kw_if) &&
935 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000936 return;
937 join(Line, *(++I));
938 }
939
940 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000941 std::vector<AnnotatedLine>::iterator E,
942 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +0000943 // No merging if the brace already is on the next line.
944 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
945 return;
946
Manuel Klimek517e8942013-01-11 17:54:10 +0000947 // First, check that the current line allows merging. This is the case if
948 // we're not in a control flow statement and the last token is an opening
949 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000950 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +0000951 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
952 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000953 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +0000954 // This gets rid of all ObjC @ keywords and methods.
955 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000956 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000957
Manuel Klimekb3987012013-05-29 14:47:47 +0000958 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000959 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000960 (Tok->getNextNonComment() == NULL ||
961 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +0000962 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +0000963 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +0000964 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000965 join(Line, *(I + 1));
966 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +0000967 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000968 // Check that we still have three lines and they fit into the limit.
969 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
970 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000971 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000972
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000973 // Second, check that the next line does not contain any braces - if it
974 // does, readability declines when putting it into a single line.
975 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
976 return;
977 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000978 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000979 return;
Manuel Klimekb3987012013-05-29 14:47:47 +0000980 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000981 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +0000982
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000983 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +0000984 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000985 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000986 Tok->MustBreakBefore)
987 return;
988
989 join(Line, *(I + 1));
990 join(Line, *(I + 2));
991 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +0000992 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000993 }
994
995 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
996 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000997 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
998 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +0000999 }
1000
Daniel Jasper995e8202013-01-14 13:08:07 +00001001 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001002 assert(!A.Last->Next);
1003 assert(!B.First->Previous);
1004 A.Last->Next = B.First;
1005 B.First->Previous = A.Last;
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;
Daniel Jasper995e8202013-01-14 13:08:07 +00001010 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001011 }
1012
Daniel Jasper6f21a982013-03-13 07:49:51 +00001013 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001014 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1015 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1016 Ranges[i].getBegin()) &&
1017 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1018 Range.getBegin()))
1019 return true;
1020 }
1021 return false;
1022 }
1023
1024 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001025 const FormatToken *First = TheLine.First;
1026 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001027 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001028 First->WhitespaceRange.getBegin().getLocWithOffset(
1029 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001030 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001031 return touchesRanges(LineRange);
1032 }
1033
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001034 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1035 std::vector<AnnotatedLine>::iterator E) {
1036 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001037 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001038 return false;
1039 if (touchesLine(*I))
1040 return true;
1041 }
1042 return false;
1043 }
1044
Daniel Jasperf3023542013-03-07 20:50:00 +00001045 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001046 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001047 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001048 First->WhitespaceRange.getBegin(),
1049 First->WhitespaceRange.getBegin().getLocWithOffset(
1050 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001051 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001052 }
1053
1054 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001055 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001056 }
1057
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001058 /// \brief Add a new line and the required indent before the first Token
1059 /// of the \c UnwrappedLine if there was no structural parsing error.
1060 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001061 void formatFirstToken(const FormatToken &RootToken,
1062 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001063 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001064 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001065 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001066 // Remove empty lines before "}" where applicable.
1067 if (RootToken.is(tok::r_brace) &&
1068 (!RootToken.Next ||
1069 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1070 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001071 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001072 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001073
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001074 // Insert extra new line before access specifiers.
1075 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001076 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001077 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001078
Manuel Klimekb3987012013-05-29 14:47:47 +00001079 Whitespaces.replaceWhitespace(
1080 RootToken, Newlines, Indent, Indent,
1081 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001082 }
1083
Daniel Jasperbac016b2012-12-03 18:12:45 +00001084 FormatStyle Style;
1085 Lexer &Lex;
1086 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001087 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001088 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001089 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001090
1091 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001092 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001093};
1094
Craig Topper83f81d72013-06-30 22:29:28 +00001095} // end anonymous namespace
1096
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001097tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1098 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001099 std::vector<CharSourceRange> Ranges) {
1100 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001101 return formatter.format();
1102}
1103
Daniel Jasper8a999452013-05-16 10:40:07 +00001104tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1105 std::vector<tooling::Range> Ranges,
1106 StringRef FileName) {
1107 FileManager Files((FileSystemOptions()));
1108 DiagnosticsEngine Diagnostics(
1109 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1110 new DiagnosticOptions);
1111 SourceManager SourceMgr(Diagnostics, Files);
1112 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1113 const clang::FileEntry *Entry =
1114 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1115 SourceMgr.overrideFileContents(Entry, Buf);
1116 FileID ID =
1117 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001118 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1119 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001120 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1121 std::vector<CharSourceRange> CharRanges;
1122 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1123 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1124 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1125 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1126 }
1127 return reformat(Style, Lex, SourceMgr, CharRanges);
1128}
1129
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001130LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001131 LangOptions LangOpts;
1132 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001133 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001134 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001135 LangOpts.Bool = 1;
1136 LangOpts.ObjC1 = 1;
1137 LangOpts.ObjC2 = 1;
1138 return LangOpts;
1139}
1140
Daniel Jaspercd162382013-01-07 13:26:07 +00001141} // namespace format
1142} // namespace clang