blob: 290f0597f578917a2778586d65d20f1f7f9e5e1f [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
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.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"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod71ec162013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod71ec162013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimek44135b82013-05-13 12:51:40 +000038 static void enumeration(IO &IO,
39 clang::format::FormatStyle::LanguageStandard &Value) {
40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
41 IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
42 IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
43 }
44};
45
Daniel Jasper1fb8d882013-05-14 09:30:02 +000046template <>
Manuel Klimek44135b82013-05-13 12:51:40 +000047struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
48 static void
49 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
50 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
51 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
52 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
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);
93 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper893ea8d2013-07-31 23:55:15 +000094 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod71ec162013-05-07 15:32:14 +000095 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
96 Style.AllowAllParametersOfDeclarationOnNextLine);
97 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
98 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasperf11bbb92013-05-16 12:12:21 +000099 IO.mapOptional("AllowShortLoopsOnASingleLine",
100 Style.AllowShortLoopsOnASingleLine);
Daniel Jasperbbc87762013-05-29 12:07:31 +0000101 IO.mapOptional("AlwaysBreakTemplateDeclarations",
102 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko56312022013-07-04 12:02:44 +0000103 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
104 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000105 IO.mapOptional("BreakBeforeBinaryOperators",
106 Style.BreakBeforeBinaryOperators);
107 IO.mapOptional("BreakConstructorInitializersBeforeComma",
108 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000109 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
110 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
111 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
112 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
113 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000114 IO.mapOptional("ExperimentalAutoDetectBinPacking",
115 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000116 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
117 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jaspereff18b92013-07-31 23:16:02 +0000118 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000119 IO.mapOptional("ObjCSpaceBeforeProtocolList",
120 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +0000121 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
122 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000123 IO.mapOptional("PenaltyBreakFirstLessLess",
124 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000125 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
126 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
127 Style.PenaltyReturnTypeOnItsOwnLine);
128 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
129 IO.mapOptional("SpacesBeforeTrailingComments",
130 Style.SpacesBeforeTrailingComments);
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000131 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000132 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000133 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000134 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimek44135b82013-05-13 12:51:40 +0000135 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000136 IO.mapOptional("IndentFunctionDeclarationAfterType",
137 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000138 }
139};
140}
141}
142
Daniel Jasperbac016b2012-12-03 18:12:45 +0000143namespace clang {
144namespace format {
145
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000146void setDefaultPenalties(FormatStyle &Style) {
147 Style.PenaltyBreakComment = 45;
Daniel Jasper9637dda2013-07-15 14:33:14 +0000148 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000149 Style.PenaltyBreakString = 1000;
150 Style.PenaltyExcessCharacter = 1000000;
151}
152
Daniel Jasperbac016b2012-12-03 18:12:45 +0000153FormatStyle getLLVMStyle() {
154 FormatStyle LLVMStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000155 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000156 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000157 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000158 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000160 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko56312022013-07-04 12:02:44 +0000161 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000162 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000163 LLVMStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000164 LLVMStyle.BreakBeforeBinaryOperators = false;
165 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
166 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000167 LLVMStyle.ColumnLimit = 80;
168 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000169 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000170 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000171 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000172 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000173 LLVMStyle.IndentFunctionDeclarationAfterType = false;
174 LLVMStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000175 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000176 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000177 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000178 LLVMStyle.PointerBindsToType = false;
179 LLVMStyle.SpacesBeforeTrailingComments = 1;
180 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000181 LLVMStyle.UseTab = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000182
183 setDefaultPenalties(LLVMStyle);
184 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
185
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186 return LLVMStyle;
187}
188
189FormatStyle getGoogleStyle() {
190 FormatStyle GoogleStyle;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000191 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000192 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000193 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000194 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000195 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper1bee0732013-05-23 18:05:18 +0000196 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko56312022013-07-04 12:02:44 +0000197 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000198 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000199 GoogleStyle.BinPackParameters = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000200 GoogleStyle.BreakBeforeBinaryOperators = false;
201 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
202 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000203 GoogleStyle.ColumnLimit = 80;
204 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000205 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000206 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000207 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000208 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000209 GoogleStyle.IndentFunctionDeclarationAfterType = true;
210 GoogleStyle.IndentWidth = 2;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000211 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000212 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Weber5f500df2013-01-10 20:12:55 +0000213 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkofb594862013-05-06 14:11:27 +0000214 GoogleStyle.PointerBindsToType = true;
215 GoogleStyle.SpacesBeforeTrailingComments = 2;
216 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek7c9a93e2013-05-13 09:22:11 +0000217 GoogleStyle.UseTab = false;
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000218
219 setDefaultPenalties(GoogleStyle);
220 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
221
Daniel Jasperbac016b2012-12-03 18:12:45 +0000222 return GoogleStyle;
223}
224
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000225FormatStyle getChromiumStyle() {
226 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000227 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +0000228 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperf11bbb92013-05-16 12:12:21 +0000229 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000230 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000231 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000232 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000233 return ChromiumStyle;
234}
235
Alexander Kornienkofb594862013-05-06 14:11:27 +0000236FormatStyle getMozillaStyle() {
237 FormatStyle MozillaStyle = getLLVMStyle();
238 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
239 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
240 MozillaStyle.DerivePointerBinding = true;
241 MozillaStyle.IndentCaseLabels = true;
242 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
243 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
244 MozillaStyle.PointerBindsToType = true;
245 return MozillaStyle;
246}
247
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000248FormatStyle getWebKitStyle() {
249 FormatStyle Style = getLLVMStyle();
Daniel Jaspereff18b92013-07-31 23:16:02 +0000250 Style.AccessModifierOffset = -4;
Daniel Jasper893ea8d2013-07-31 23:55:15 +0000251 Style.AlignTrailingComments = false;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000252 Style.BreakBeforeBinaryOperators = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000253 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000254 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000255 Style.ColumnLimit = 0;
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000256 Style.IndentWidth = 4;
Daniel Jaspereff18b92013-07-31 23:16:02 +0000257 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000258 Style.PointerBindsToType = true;
259 return Style;
260}
261
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000262bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000263 if (Name.equals_lower("llvm"))
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000264 *Style = getLLVMStyle();
265 else if (Name.equals_lower("chromium"))
266 *Style = getChromiumStyle();
267 else if (Name.equals_lower("mozilla"))
268 *Style = getMozillaStyle();
269 else if (Name.equals_lower("google"))
270 *Style = getGoogleStyle();
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000271 else if (Name.equals_lower("webkit"))
272 *Style = getWebKitStyle();
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000273 else
274 return false;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000275
Alexander Kornienko885f87b2013-05-19 00:53:30 +0000276 return true;
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000277}
278
279llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko107db3c2013-05-20 15:18:01 +0000280 if (Text.trim().empty())
281 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000282 llvm::yaml::Input Input(Text);
283 Input >> *Style;
284 return Input.error();
285}
286
287std::string configurationAsText(const FormatStyle &Style) {
288 std::string Text;
289 llvm::raw_string_ostream Stream(Text);
290 llvm::yaml::Output Output(Stream);
291 // We use the same mapping method for input and output, so we need a non-const
292 // reference here.
293 FormatStyle NonConstStyle = Style;
294 Output << NonConstStyle;
Alexander Kornienko2b6acb62013-05-13 12:56:35 +0000295 return Stream.str();
Alexander Kornienkod71ec162013-05-07 15:32:14 +0000296}
297
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000298// Returns the length of everything up to the first possible line break after
299// the ), ], } or > matching \c Tok.
Manuel Klimekb3987012013-05-29 14:47:47 +0000300static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000301 if (Tok.MatchingParen == NULL)
302 return 0;
Manuel Klimekb3987012013-05-29 14:47:47 +0000303 FormatToken *End = Tok.MatchingParen;
304 while (End->Next && !End->Next->CanBreakBefore) {
305 End = End->Next;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000306 }
307 return End->TotalLength - Tok.TotalLength + 1;
308}
309
Craig Topper83f81d72013-06-30 22:29:28 +0000310namespace {
311
Daniel Jasperbac016b2012-12-03 18:12:45 +0000312class UnwrappedLineFormatter {
313public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000314 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000315 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimekb3987012013-05-29 14:47:47 +0000316 const FormatToken *RootToken,
Alexander Kornienko00895102013-06-05 14:09:10 +0000317 WhitespaceManager &Whitespaces,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000318 encoding::Encoding Encoding,
319 bool BinPackInconclusiveFunctions)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000320 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000321 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000322 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
323 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000324
Manuel Klimekd4397b92013-01-04 23:34:14 +0000325 /// \brief Formats an \c UnwrappedLine.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000326 void format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000327 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000328 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000329 State.Column = FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +0000330 State.NextToken = RootToken;
Daniel Jasper2a409b62013-07-08 14:34:09 +0000331 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
332 /*AvoidBinPacking=*/false,
333 /*NoLineBreak=*/false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000334 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000335 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000336 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000337 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000338 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000339 State.IgnoreStackForComparison = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000340
341 // The first token has already been indented and thus consumed.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000342 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000343
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000344 if (Style.ColumnLimit == 0) {
345 formatWithoutColumnLimit(State);
346 return;
347 }
348
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000349 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000350 unsigned ColumnLimit = Style.ColumnLimit;
351 if (NextLine && NextLine->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000352 !NextLine->First->HasUnescapedNewline)
Daniel Jaspera4d46212013-02-28 11:05:57 +0000353 ColumnLimit = getColumnLimit();
354 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000355 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000356 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000357 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000358 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000359
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000360 // If the ObjC method declaration does not fit on a line, we should format
361 // it with one arg per line.
362 if (Line.Type == LT_ObjCMethodDecl)
363 State.Stack.back().BreakBeforeParameter = true;
364
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000365 // Find best solution in solution space.
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000366 analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000367 }
368
369private:
Manuel Klimekb3987012013-05-29 14:47:47 +0000370 void DebugTokenState(const FormatToken &FormatTok) {
371 const Token &Tok = FormatTok.Tok;
Alexander Kornienkodd256312013-05-10 11:56:10 +0000372 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000373 Tok.getLength());
Alexander Kornienkodd256312013-05-10 11:56:10 +0000374 llvm::dbgs();
Manuel Klimekca547db2013-01-16 14:55:28 +0000375 }
376
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000377 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000378 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000379 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000380 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
381 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000382 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000383 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasper011c35d2013-07-12 11:19:37 +0000384 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
385 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000386
Daniel Jasperbac016b2012-12-03 18:12:45 +0000387 /// \brief The position to which a specific parenthesis level needs to be
388 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000389 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000391 /// \brief The position of the last space on each level.
392 ///
393 /// Used e.g. to break like:
394 /// functionCall(Parameter, otherCall(
395 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000396 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000397
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000398 /// \brief The position the first "<<" operator encountered on each level.
399 ///
400 /// Used to align "<<" operators. 0 if no such operator has been encountered
401 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000402 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000403
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000404 /// \brief Whether a newline needs to be inserted before the block's closing
405 /// brace.
406 ///
407 /// We only want to insert a newline before the closing brace if there also
408 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000409 bool BreakBeforeClosingBrace;
410
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000411 /// \brief The column of a \c ? in a conditional expression;
412 unsigned QuestionColumn;
413
Daniel Jasperf343cab2013-01-31 14:59:26 +0000414 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
415 /// lines, in this context.
416 bool AvoidBinPacking;
417
418 /// \brief Break after the next comma (or all the commas in this context if
419 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000420 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000421
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000422 /// \brief Line breaking in this context would break a formatting rule.
423 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000424
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000425 /// \brief The position of the colon in an ObjC method declaration/call.
426 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000427
Daniel Jasper24849712013-03-01 16:48:32 +0000428 /// \brief The start of the most recent function in a builder-type call.
429 unsigned StartOfFunctionCall;
430
Daniel Jasper011c35d2013-07-12 11:19:37 +0000431 /// \brief Contains the start of array subscript expressions, so that they
432 /// can be aligned.
433 unsigned StartOfArraySubscripts;
434
Daniel Jasper37911302013-04-02 14:33:13 +0000435 /// \brief If a nested name specifier was broken over multiple lines, this
436 /// contains the start column of the second line. Otherwise 0.
437 unsigned NestedNameSpecifierContinuation;
438
439 /// \brief If a call expression was broken over multiple lines, this
440 /// contains the start column of the second line. Otherwise 0.
441 unsigned CallContinuation;
442
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000443 /// \brief The column of the first variable name in a variable declaration.
444 ///
445 /// Used to align further variables if necessary.
446 unsigned VariablePos;
447
Daniel Jasper88cc5622013-07-08 14:25:23 +0000448 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000449 ///
Daniel Jasper88cc5622013-07-08 14:25:23 +0000450 /// The first line break in a certain \c ParenState causes extra penalty so
451 /// that clang-format prefers similar breaks, i.e. breaks in the same
452 /// parenthesis.
453 bool ContainsLineBreak;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000454
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000455 bool operator<(const ParenState &Other) const {
456 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000457 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000458 if (LastSpace != Other.LastSpace)
459 return LastSpace < Other.LastSpace;
460 if (FirstLessLess != Other.FirstLessLess)
461 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000462 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
463 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000464 if (QuestionColumn != Other.QuestionColumn)
465 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000466 if (AvoidBinPacking != Other.AvoidBinPacking)
467 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000468 if (BreakBeforeParameter != Other.BreakBeforeParameter)
469 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000470 if (NoLineBreak != Other.NoLineBreak)
471 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000472 if (ColonPos != Other.ColonPos)
473 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000474 if (StartOfFunctionCall != Other.StartOfFunctionCall)
475 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000476 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
477 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasper37911302013-04-02 14:33:13 +0000478 if (CallContinuation != Other.CallContinuation)
479 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000480 if (VariablePos != Other.VariablePos)
481 return VariablePos < Other.VariablePos;
Daniel Jasper88cc5622013-07-08 14:25:23 +0000482 if (ContainsLineBreak != Other.ContainsLineBreak)
483 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperb3123142013-01-12 07:36:22 +0000484 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000485 }
486 };
487
488 /// \brief The current state when indenting a unwrapped line.
489 ///
490 /// As the indenting tries different combinations this is copied by value.
491 struct LineState {
492 /// \brief The number of used columns in the current line.
493 unsigned Column;
494
495 /// \brief The token that needs to be next formatted.
Manuel Klimekb3987012013-05-29 14:47:47 +0000496 const FormatToken *NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000497
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000498 /// \brief \c true if this line contains a continued for-loop section.
499 bool LineContainsContinuedForLoopSection;
500
Daniel Jasper29f123b2013-02-08 15:28:42 +0000501 /// \brief The level of nesting inside (), [], <> and {}.
502 unsigned ParenLevel;
503
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000504 /// \brief The \c ParenLevel at the start of this line.
505 unsigned StartOfLineLevel;
506
Daniel Jasper07ca5472013-07-05 09:14:35 +0000507 /// \brief The lowest \c ParenLevel on the current line.
508 unsigned LowestLevelOnLine;
Daniel Jasper259a0382013-05-27 11:50:16 +0000509
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000510 /// \brief The start column of the string literal, if we're in a string
511 /// literal sequence, 0 otherwise.
512 unsigned StartOfStringLiteral;
513
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000514 /// \brief A stack keeping track of properties applying to parenthesis
515 /// levels.
516 std::vector<ParenState> Stack;
517
Daniel Jasper54b4e442013-05-22 05:27:42 +0000518 /// \brief Ignore the stack of \c ParenStates for state comparison.
519 ///
520 /// In long and deeply nested unwrapped lines, the current algorithm can
521 /// be insufficient for finding the best formatting with a reasonable amount
522 /// of time and memory. Setting this flag will effectively lead to the
523 /// algorithm not analyzing some combinations. However, these combinations
524 /// rarely contain the optimal solution: In short, accepting a higher
525 /// penalty early would need to lead to different values in the \c
526 /// ParenState stack (in an otherwise identical state) and these different
527 /// values would need to lead to a significant amount of avoided penalty
528 /// later.
529 ///
530 /// FIXME: Come up with a better algorithm instead.
531 bool IgnoreStackForComparison;
532
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000533 /// \brief Comparison operator to be able to used \c LineState in \c map.
534 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000535 if (NextToken != Other.NextToken)
536 return NextToken < Other.NextToken;
537 if (Column != Other.Column)
538 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000539 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000540 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000541 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000542 if (ParenLevel != Other.ParenLevel)
543 return ParenLevel < Other.ParenLevel;
544 if (StartOfLineLevel != Other.StartOfLineLevel)
545 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000546 if (LowestLevelOnLine != Other.LowestLevelOnLine)
547 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000548 if (StartOfStringLiteral != Other.StartOfStringLiteral)
549 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper54b4e442013-05-22 05:27:42 +0000550 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
551 return false;
Daniel Jasperd7896702013-02-19 09:28:55 +0000552 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000553 }
554 };
555
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000556 /// \brief Formats the line starting at \p State, simply keeping all of the
557 /// input's line breaking decisions.
558 void formatWithoutColumnLimit(LineState &State) {
559 while (State.NextToken != NULL) {
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000560 bool Newline = mustBreak(State) ||
561 (canBreak(State) && State.NextToken->NewlinesBefore > 0);
Daniel Jaspere05dc6d2013-07-24 13:10:59 +0000562 addTokenToState(Newline, /*DryRun=*/false, State);
563 }
564 }
565
Daniel Jasper20409152012-12-04 14:54:30 +0000566 /// \brief Appends the next token to \p State and updates information
567 /// necessary for indentation.
568 ///
Nico Weber1907c572013-06-26 02:42:46 +0000569 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper20409152012-12-04 14:54:30 +0000570 /// line break and necessary indentation otherwise.
571 ///
572 /// If \p DryRun is \c false, also creates and stores the required
573 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000574 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000575 const FormatToken &Current = *State.NextToken;
576 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000577
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000578 // Extra penalty that needs to be added because of the way certain line
579 // breaks are chosen.
580 unsigned ExtraPenalty = 0;
581
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000582 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimekad3094b2013-05-23 10:56:37 +0000583 // FIXME: Is this correct?
Manuel Klimekb3987012013-05-29 14:47:47 +0000584 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
585 State.NextToken->WhitespaceRange.getEnd()) -
586 SourceMgr.getSpellingColumnNumber(
587 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienko00895102013-06-05 14:09:10 +0000588 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimekb3987012013-05-29 14:47:47 +0000589 State.NextToken = State.NextToken->Next;
Manuel Klimek8092a942013-02-20 10:15:13 +0000590 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000591 }
592
Daniel Jasper3776ef32013-04-03 07:21:51 +0000593 // If we are continuing an expression, we want to indent an extra 4 spaces.
594 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000595 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000596 if (Newline) {
Daniel Jasper88cc5622013-07-08 14:25:23 +0000597 State.Stack.back().ContainsLineBreak = true;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000598 if (Current.is(tok::r_brace)) {
Daniel Jasper0de1c4d2013-07-09 09:06:29 +0000599 if (Current.BlockKind == BK_BracedInit)
600 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
601 else
Daniel Jasper15ec3a82013-07-11 21:27:40 +0000602 State.Column = FirstIndent;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000603 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000604 State.StartOfStringLiteral != 0) {
605 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000606 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000607 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000608 State.Stack.back().FirstLessLess != 0) {
609 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000610 } else if (Current.isOneOf(tok::period, tok::arrow) &&
611 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000612 if (State.Stack.back().CallContinuation == 0) {
613 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000614 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000615 } else {
616 State.Column = State.Stack.back().CallContinuation;
617 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000618 } else if (Current.Type == TT_ConditionalExpr) {
619 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000620 } else if (Previous.is(tok::comma) &&
621 State.Stack.back().VariablePos != 0) {
622 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000623 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6561f6a2013-07-09 07:43:55 +0000624 ((Current.Type == TT_StartOfName ||
625 Current.is(tok::kw_operator)) &&
626 State.ParenLevel == 0 &&
Manuel Klimeka9a7f102013-06-21 17:25:42 +0000627 (!Style.IndentFunctionDeclarationAfterType ||
628 Line.StartsDefinition))) {
Daniel Jasper37911302013-04-02 14:33:13 +0000629 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000630 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienko00895102013-06-05 14:09:10 +0000631 if (State.Stack.back().ColonPos > Current.CodePointCount) {
632 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000633 } else {
634 State.Column = State.Stack.back().Indent;
Alexander Kornienko00895102013-06-05 14:09:10 +0000635 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000636 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000637 } else if (Current.is(tok::l_square) &&
638 Current.Type != TT_ObjCMethodExpr) {
639 if (State.Stack.back().StartOfArraySubscripts != 0)
640 State.Column = State.Stack.back().StartOfArraySubscripts;
641 else
642 State.Column = ContinuationIndent;
Daniel Jasperb2f063a2013-05-08 10:00:18 +0000643 } else if (Current.Type == TT_StartOfName ||
644 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000645 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000646 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000647 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000648 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000649 // Ensure that we fall back to indenting 4 spaces instead of just
650 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000651 if (State.Column == FirstIndent)
652 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000653 }
654
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000655 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000656 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper11e13802013-05-08 14:12:04 +0000657 if ((Previous.isOneOf(tok::comma, tok::semi) &&
658 !State.Stack.back().AvoidBinPacking) ||
659 Previous.Type == TT_BinaryOperator)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000660 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper33f4b902013-05-15 09:35:08 +0000661 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
662 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000663
Manuel Klimek060143e2013-01-02 18:33:23 +0000664 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000665 unsigned NewLines = 1;
Alexander Kornienkoe3f11972013-06-12 19:04:12 +0000666 if (Current.is(tok::comment))
Manuel Klimekb3987012013-05-29 14:47:47 +0000667 NewLines = std::max(
668 NewLines,
669 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000670 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
671 State.Column, Line.InPPDirective);
Manuel Klimek060143e2013-01-02 18:33:23 +0000672 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000673
Daniel Jaspere1f9a8e2013-07-11 13:48:16 +0000674 if (!Current.isTrailingComment())
675 State.Stack.back().LastSpace = State.Column;
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000676 if (Current.isOneOf(tok::arrow, tok::period) &&
677 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienko00895102013-06-05 14:09:10 +0000678 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000679 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000680 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000681
682 // Any break on this level means that the parent level has been broken
683 // and we need to avoid bin packing there.
684 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
685 State.Stack[i].BreakBeforeParameter = true;
686 }
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000687 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper01218ff2013-04-15 22:36:37 +0000688 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasper33f4b902013-05-15 09:35:08 +0000689 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasper11e13802013-05-08 14:12:04 +0000690 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000691 State.Stack.back().BreakBeforeParameter = true;
692
Daniel Jasper237d4c12013-02-23 21:01:55 +0000693 // If we break after {, we should also break before the corresponding }.
694 if (Previous.is(tok::l_brace))
695 State.Stack.back().BreakBeforeClosingBrace = true;
696
697 if (State.Stack.back().AvoidBinPacking) {
698 // If we are breaking after '(', '{', '<', this is not bin packing
699 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasperd741f022013-05-14 20:39:56 +0000700 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
701 Previous.Type == TT_BinaryOperator) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000702 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
703 Line.MustBeDeclaration))
704 State.Stack.back().BreakBeforeParameter = true;
705 }
Daniel Jasperfaec47b2013-07-11 20:41:21 +0000706
707 // Breaking before the first "<<" is generally not desirable.
708 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
709 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
710
Daniel Jasperbac016b2012-12-03 18:12:45 +0000711 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000712 if (Current.is(tok::equal) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000713 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000714 State.Stack.back().VariablePos == 0) {
715 State.Stack.back().VariablePos = State.Column;
716 // Move over * and & if they are bound to the variable name.
Manuel Klimekb3987012013-05-29 14:47:47 +0000717 const FormatToken *Tok = &Previous;
Alexander Kornienko00895102013-06-05 14:09:10 +0000718 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
719 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000720 if (Tok->SpacesRequiredBefore != 0)
721 break;
Manuel Klimekb3987012013-05-29 14:47:47 +0000722 Tok = Tok->Previous;
Daniel Jasperadc0f092013-04-05 09:38:50 +0000723 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000724 if (Previous.PartOfMultiVariableDeclStmt)
725 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
726 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000727
Daniel Jasper729a7432013-02-11 12:36:37 +0000728 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000729
Daniel Jasperbac016b2012-12-03 18:12:45 +0000730 if (!DryRun)
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000731 Whitespaces.replaceWhitespace(Current, 0, Spaces,
732 State.Column + Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000733
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000734 if (Current.Type == TT_ObjCSelectorName &&
735 State.Stack.back().ColonPos == 0) {
736 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko00895102013-06-05 14:09:10 +0000737 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000738 State.Stack.back().ColonPos =
739 State.Stack.back().Indent + Current.LongestObjCSelectorName;
740 else
741 State.Stack.back().ColonPos =
Alexander Kornienko00895102013-06-05 14:09:10 +0000742 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000743 }
744
Daniel Jasperac3223e2013-04-10 09:49:49 +0000745 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000746 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000747 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000748 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
749 State.Stack.back().AvoidBinPacking)
750 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000751
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000752 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000753 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000754 // Treat the condition inside an if as if it was a second function
755 // parameter, i.e. let nested calls have an indent of 4.
756 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000757 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000758 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000759 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000760 Previous.Type == TT_ConditionalExpr ||
761 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000762 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper512843a2013-05-27 12:45:09 +0000763 Current.FakeLParens.empty()))
764 // Always indent relative to the RHS of the expression unless this is a
765 // simple assignment without binary expression on the RHS.
Daniel Jasperae8699b2013-01-28 09:35:24 +0000766 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000767 else if (Previous.Type == TT_InheritanceColon)
768 State.Stack.back().Indent = State.Column;
Daniel Jasperb1491792013-07-09 11:57:27 +0000769 else if (Previous.opensScope()) {
770 // If a function has multiple parameters (including a single parameter
Daniel Jasper2ca37412013-07-09 14:36:48 +0000771 // that is a binary expression) or a trailing call, indent all
Daniel Jasperb1491792013-07-09 11:57:27 +0000772 // parameters from the opening parenthesis. This avoids confusing
773 // indents like:
774 // OuterFunction(InnerFunctionCall(
775 // ParameterToInnerFunction),
776 // SecondParameterToOuterFunction);
777 bool HasMultipleParameters = !Current.FakeLParens.empty();
778 bool HasTrailingCall = false;
779 if (Previous.MatchingParen) {
780 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
781 if (Next && Next->isOneOf(tok::period, tok::arrow))
782 HasTrailingCall = true;
783 }
784 if (HasMultipleParameters || HasTrailingCall)
785 State.Stack.back().LastSpace = State.Column;
786 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000787 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000788
Daniel Jasper0fde9502013-07-12 11:37:05 +0000789 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper20409152012-12-04 14:54:30 +0000790 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000791
Daniel Jasper20409152012-12-04 14:54:30 +0000792 /// \brief Mark the next token as consumed in \p State and modify its stacks
793 /// accordingly.
Daniel Jasper0fde9502013-07-12 11:37:05 +0000794 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimekb3987012013-05-29 14:47:47 +0000795 const FormatToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000796 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000797
Daniel Jasper6cabab42013-02-14 08:42:54 +0000798 if (Current.Type == TT_InheritanceColon)
799 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000800 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
801 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000802 if (Current.is(tok::l_square) &&
803 State.Stack.back().StartOfArraySubscripts == 0)
804 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000805 if (Current.is(tok::question))
806 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper07ca5472013-07-05 09:14:35 +0000807 if (!Current.opensScope() && !Current.closesScope())
808 State.LowestLevelOnLine =
809 std::min(State.LowestLevelOnLine, State.ParenLevel);
810 if (Current.isOneOf(tok::period, tok::arrow) &&
811 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
812 State.Stack.back().StartOfFunctionCall =
813 Current.LastInChainOfCalls ? 0
814 : State.Column + Current.CodePointCount;
Daniel Jasper7d812812013-02-21 15:00:29 +0000815 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek07a64ec2013-05-13 08:42:42 +0000816 // Indent 2 from the column, so:
817 // SomeClass::SomeClass()
818 // : First(...), ...
819 // Next(...)
820 // ^ line up here.
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000821 if (!Style.BreakConstructorInitializersBeforeComma)
822 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000823 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
824 State.Stack.back().AvoidBinPacking = true;
825 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000826 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000827
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000828 // If return returns a binary expression, align after it.
829 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
830 State.Stack.back().LastSpace = State.Column + 7;
831
Daniel Jasper3776ef32013-04-03 07:21:51 +0000832 // In ObjC method declaration we align on the ":" of parameters, but we need
833 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000834 if (Current.Type == TT_ObjCMethodSpecifier)
835 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000836
Daniel Jasper29f123b2013-02-08 15:28:42 +0000837 // Insert scopes created by fake parenthesis.
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000838 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000839 // Don't add extra indentation for the first fake parenthesis after
840 // 'return', assignements or opening <({[. The indentation for these cases
841 // is special cased.
842 bool SkipFirstExtraIndent =
843 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000844 (Previous && (Previous->opensScope() ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000845 Previous->getPrecedence() == prec::Assignment));
Craig Topper163fbf82013-07-08 03:55:09 +0000846 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000847 I = Current.FakeLParens.rbegin(),
848 E = Current.FakeLParens.rend();
849 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000850 ParenState NewParenState = State.Stack.back();
Daniel Jasper88cc5622013-07-08 14:25:23 +0000851 NewParenState.ContainsLineBreak = false;
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000852 NewParenState.Indent =
853 std::max(std::max(State.Column, NewParenState.Indent),
854 State.Stack.back().LastSpace);
855
856 // Always indent conditional expressions. Never indent expression where
857 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
858 // prec::Assignment) as those have different indentation rules. Indent
859 // other expression, unless the indentation needs to be skipped.
860 if (*I == prec::Conditional ||
Daniel Jaspere8b10d32013-07-26 16:56:36 +0000861 (!SkipFirstExtraIndent && *I > prec::Assignment &&
862 !Style.BreakBeforeBinaryOperators))
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000863 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000864 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000865 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000866 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000867 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000868 }
869
Daniel Jaspercf225b62012-12-24 13:43:52 +0000870 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000871 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000872 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000873 unsigned NewIndent;
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000874 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000875 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000876 if (Current.is(tok::l_brace)) {
Daniel Jasperb5dc3f42013-07-16 18:22:10 +0000877 NewIndent =
878 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko0bdc6432013-07-04 14:47:51 +0000879 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasper5ad390d2013-05-28 11:30:49 +0000880 AvoidBinPacking = NextNoComment &&
881 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek2851c162013-01-10 14:36:46 +0000882 } else {
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000883 NewIndent =
884 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperc7bd68f2013-07-10 14:02:49 +0000885 AvoidBinPacking = !Style.BinPackParameters ||
886 (Style.ExperimentalAutoDetectBinPacking &&
887 (Current.PackingKind == PPK_OnePerLine ||
888 (!BinPackInconclusiveFunctions &&
889 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek2851c162013-01-10 14:36:46 +0000890 }
Daniel Jasperfca24bc2013-04-25 13:31:51 +0000891
Daniel Jasperc3df5ff2013-05-13 09:19:24 +0000892 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
893 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000894 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000895 }
896
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000897 // If this '[' opens an ObjC call, determine whether all parameters fit into
898 // one line and put one per line if they don't.
899 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
900 Current.MatchingParen != NULL) {
901 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
902 State.Stack.back().BreakBeforeParameter = true;
903 }
904
Daniel Jaspercf225b62012-12-24 13:43:52 +0000905 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000906 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000907 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimekb3987012013-05-29 14:47:47 +0000908 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000909 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000910 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000911 --State.ParenLevel;
912 }
Daniel Jasper011c35d2013-07-12 11:19:37 +0000913 if (Current.is(tok::r_square)) {
914 // If this ends the array subscript expr, reset the corresponding value.
915 const FormatToken *NextNonComment = Current.getNextNonComment();
916 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasper9637dda2013-07-15 14:33:14 +0000917 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasper011c35d2013-07-12 11:19:37 +0000918 }
Daniel Jasper29f123b2013-02-08 15:28:42 +0000919
920 // Remove scopes created by fake parenthesis.
921 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000922 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000923 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000924 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000925 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000926
Daniel Jasper27c7f542013-05-13 20:50:15 +0000927 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000928 State.StartOfStringLiteral = State.Column;
Daniel Jasper27c7f542013-05-13 20:50:15 +0000929 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
930 tok::string_literal)) {
Daniel Jasper9a2f8d02013-05-16 04:26:02 +0000931 State.StartOfStringLiteral = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000932 }
933
Alexander Kornienko00895102013-06-05 14:09:10 +0000934 State.Column += Current.CodePointCount;
Manuel Klimek8092a942013-02-20 10:15:13 +0000935
Manuel Klimekb3987012013-05-29 14:47:47 +0000936 State.NextToken = State.NextToken->Next;
Manuel Klimek2851c162013-01-10 14:36:46 +0000937
Daniel Jasper0fde9502013-07-12 11:37:05 +0000938 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
939 Current.is(tok::string_literal))
940 return 0;
941
Manuel Klimek8092a942013-02-20 10:15:13 +0000942 return breakProtrudingToken(Current, State, DryRun);
943 }
944
945 /// \brief If the current token sticks out over the end of the line, break
946 /// it if possible.
Manuel Klimek2a9805d2013-05-14 09:04:24 +0000947 ///
948 /// \returns An extra penalty if a token was broken, otherwise 0.
949 ///
Alexander Kornienkod446f732013-07-01 13:42:42 +0000950 /// The returned penalty will cover the cost of the additional line breaks and
951 /// column limit violation in all lines except for the last one. The penalty
952 /// for the column limit violation in the last line (and in single line
953 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimekb3987012013-05-29 14:47:47 +0000954 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimeke573c3f2013-05-22 12:51:29 +0000955 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000956 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienko00895102013-06-05 14:09:10 +0000957 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000958 unsigned OriginalStartColumn =
Manuel Klimekb3987012013-05-29 14:47:47 +0000959 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +0000960 1;
Manuel Klimekde008c02013-05-27 15:23:34 +0000961
Daniel Jasper5d5b4242013-05-16 12:59:13 +0000962 if (Current.is(tok::string_literal) &&
963 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000964 // Only break up default narrow strings.
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000965 if (!Current.TokenText.startswith("\""))
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000966 return 0;
Alexander Kornienko10c26b22013-07-16 21:06:13 +0000967 // Don't break string literals with escaped newlines. As clang-format must
968 // not change the string's content, it is unlikely that we'll end up with
969 // a better format.
970 if (Current.TokenText.find("\\\n") != StringRef::npos)
971 return 0;
Daniel Jasper561211d2013-07-16 20:28:33 +0000972 // Exempts unterminated string literals from line breaking. The user will
973 // likely want to terminate the string before any line breaking is done.
974 if (Current.IsUnterminatedLiteral)
975 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000976
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000977 Token.reset(new BreakableStringLiteral(Current, StartColumn,
978 Line.InPPDirective, Encoding));
Alexander Kornienkob4b4a522013-07-16 23:47:22 +0000979 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000980 Token.reset(new BreakableBlockComment(
Alexander Kornienko00895102013-06-05 14:09:10 +0000981 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienko16a0ec62013-06-14 11:46:10 +0000982 Line.InPPDirective, Encoding));
Daniel Jasper7ff96ed2013-05-06 10:24:51 +0000983 } else if (Current.Type == TT_LineComment &&
Manuel Klimekb3987012013-05-29 14:47:47 +0000984 (Current.Previous == NULL ||
985 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko10c26b22013-07-16 21:06:13 +0000986 // Don't break line comments with escaped newlines. These look like
987 // separate line comments, but in fact contain a single line comment with
988 // multiple lines including leading whitespace and the '//' markers.
989 //
990 // FIXME: If we want to handle them correctly, we'll need to adjust
991 // leading whitespace in consecutive lines when changing indentation of
992 // the first line similar to what we do with block comments.
993 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
994 if (EscapedNewlinePos != StringRef::npos) {
995 State.Column =
996 StartColumn +
997 encoding::getCodePointCount(
998 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
999 1;
1000 return 0;
1001 }
1002
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001003 Token.reset(new BreakableLineComment(Current, StartColumn,
1004 Line.InPPDirective, Encoding));
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001005 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001006 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001007 }
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001008 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek2a9805d2013-05-14 09:04:24 +00001009 return 0;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001010
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001011 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001012 bool BreakInserted = false;
1013 unsigned Penalty = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001014 unsigned RemainingTokenColumns = 0;
Manuel Klimekde008c02013-05-27 15:23:34 +00001015 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1016 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001017 if (!DryRun)
1018 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001019 unsigned TailOffset = 0;
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001020 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001021 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +00001022 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001023 BreakableToken::Split Split =
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001024 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkod446f732013-07-01 13:42:42 +00001025 if (Split.first == StringRef::npos) {
1026 // The last line's penalty is handled in addNextStateToQueue().
1027 if (LineIndex < EndIndex - 1)
1028 Penalty += Style.PenaltyExcessCharacter *
1029 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001030 break;
Alexander Kornienkod446f732013-07-01 13:42:42 +00001031 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001032 assert(Split.first != 0);
Alexander Kornienko00895102013-06-05 14:09:10 +00001033 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001034 LineIndex, TailOffset + Split.first + Split.second,
1035 StringRef::npos);
Alexander Kornienko00895102013-06-05 14:09:10 +00001036 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienko16a0ec62013-06-14 11:46:10 +00001037 if (!DryRun)
1038 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienko2785b9a2013-06-07 16:02:52 +00001039 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
1040 : Style.PenaltyBreakComment;
1041 unsigned ColumnsUsed =
1042 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1043 if (ColumnsUsed > getColumnLimit()) {
1044 Penalty +=
1045 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
1046 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001047 TailOffset += Split.first + Split.second;
Alexander Kornienko00895102013-06-05 14:09:10 +00001048 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001049 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +00001050 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001051 }
1052
Alexander Kornienkoc36c5c22013-06-19 19:50:11 +00001053 State.Column = RemainingTokenColumns;
1054
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001055 if (BreakInserted) {
Alexander Kornienko22d0e292013-06-17 12:59:44 +00001056 // If we break the token inside a parameter list, we need to break before
1057 // the next parameter on all levels, so that the next parameter is clearly
1058 // visible. Line comments already introduce a break.
1059 if (Current.Type != TT_LineComment) {
1060 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1061 State.Stack[i].BreakBeforeParameter = true;
1062 }
1063
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001064 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +00001065 }
Manuel Klimek8092a942013-02-20 10:15:13 +00001066 return Penalty;
1067 }
1068
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001069 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001070 // In preprocessor directives reserve two chars for trailing " \"
1071 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001072 }
1073
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001074 /// \brief An edge in the solution space from \c Previous->State to \c State,
1075 /// inserting a newline dependent on the \c NewLine.
1076 struct StateNode {
1077 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +00001078 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001079 LineState State;
1080 bool NewLine;
1081 StateNode *Previous;
1082 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001083
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001084 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1085 ///
1086 /// In case of equal penalties, we want to prefer states that were inserted
1087 /// first. During state generation we make sure that we insert states first
1088 /// that break the line as late as possible.
1089 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1090
1091 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1092 /// \c State has the given \c OrderedPenalty.
1093 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1094
1095 /// \brief The BFS queue type.
1096 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1097 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001098
1099 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001100 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001101 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1102 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1103 /// find the shortest path (the one with lowest penalty) from \p InitialState
1104 /// to a state where all tokens are placed.
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001105 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001106 std::set<LineState> Seen;
1107
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001108 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001109 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001110 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1111 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1112 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001113
1114 // While not empty, take first element and follow edges.
1115 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001116 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001117 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001118 if (Node->State.NextToken == NULL) {
Alexander Kornienkodd256312013-05-10 11:56:10 +00001119 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001120 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001121 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001122 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001123
Daniel Jasper54b4e442013-05-22 05:27:42 +00001124 // Cut off the analysis of certain solutions if the analysis gets too
1125 // complex. See description of IgnoreStackForComparison.
1126 if (Count > 10000)
1127 Node->State.IgnoreStackForComparison = true;
1128
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001129 if (!Seen.insert(Node->State).second)
1130 // State already examined with lower penalty.
1131 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001132
Nico Weber27268772013-06-26 00:30:14 +00001133 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1134 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001135 }
1136
1137 if (Queue.empty())
1138 // We were unable to find a solution, do nothing.
1139 // FIXME: Add diagnostic?
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001140 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001141
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001142 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001143 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienkodd256312013-05-10 11:56:10 +00001144 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1145 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001146 }
1147
1148 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek9c333b92013-05-29 15:10:11 +00001149 std::deque<StateNode *> Path;
1150 // We do not need a break before the initial token.
1151 while (Current->Previous) {
1152 Path.push_front(Current);
1153 Current = Current->Previous;
1154 }
1155 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1156 I != E; ++I) {
1157 DEBUG({
1158 if ((*I)->NewLine) {
1159 llvm::dbgs() << "Penalty for splitting before "
1160 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1161 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1162 }
1163 });
1164 addTokenToState((*I)->NewLine, false, State);
1165 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001166 }
1167
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001168 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001169 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001170 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001171 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001172 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1173 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001174 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001175 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001176 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001177 return;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001178 if (NewLine) {
1179 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1180 Penalty += 15;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001181 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasper88cc5622013-07-08 14:25:23 +00001182 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001183
1184 StateNode *Node = new (Allocator.Allocate())
1185 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +00001186 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001187 if (Node->State.Column > getColumnLimit()) {
1188 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +00001189 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001190 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001191
1192 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1193 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001194 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001195
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001196 /// \brief Returns \c true, if a line break after \p State is allowed.
1197 bool canBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001198 const FormatToken &Current = *State.NextToken;
1199 const FormatToken &Previous = *Current.Previous;
1200 assert(&Previous == Current.Previous);
Daniel Jasper399914b2013-05-17 09:35:01 +00001201 if (!Current.CanBreakBefore &&
1202 !(Current.is(tok::r_brace) &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001203 State.Stack.back().BreakBeforeClosingBrace))
1204 return false;
Daniel Jasper399914b2013-05-17 09:35:01 +00001205 // The opening "{" of a braced list has to be on the same line as the first
1206 // element if it is nested in another braced init list or function call.
1207 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001208 Previous.Previous &&
1209 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper399914b2013-05-17 09:35:01 +00001210 return false;
Daniel Jasper259a0382013-05-27 11:50:16 +00001211 // This prevents breaks like:
1212 // ...
1213 // SomeParameter, OtherParameter).DoSomething(
1214 // ...
1215 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper07ca5472013-07-05 09:14:35 +00001216 if (Previous.opensScope() &&
1217 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper259a0382013-05-27 11:50:16 +00001218 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +00001219 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001220 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001221
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001222 /// \brief Returns \c true, if a line break after \p State is mandatory.
1223 bool mustBreak(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001224 const FormatToken &Current = *State.NextToken;
1225 const FormatToken &Previous = *Current.Previous;
Daniel Jasper11e13802013-05-08 14:12:04 +00001226 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001227 return true;
Daniel Jasperb5dc3f42013-07-16 18:22:10 +00001228 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1229 State.Stack.back().BreakBeforeClosingBrace)
1230 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001231 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001232 return true;
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001233 if (Style.BreakConstructorInitializersBeforeComma) {
1234 if (Previous.Type == TT_CtorInitializerComma)
1235 return false;
1236 if (Current.Type == TT_CtorInitializerComma)
1237 return true;
1238 }
Daniel Jasper11e13802013-05-08 14:12:04 +00001239 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1240 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001241 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper11e13802013-05-08 14:12:04 +00001242 !Current.isTrailingComment() &&
1243 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001244 return true;
Daniel Jasper215c57f2013-07-17 15:38:19 +00001245 if (Style.AlwaysBreakBeforeMultilineStrings &&
1246 State.Column > State.Stack.back().Indent &&
1247 Current.is(tok::string_literal) && Previous.isNot(tok::lessless) &&
1248 Previous.Type != TT_InlineASMColon &&
1249 ((Current.getNextNonComment() &&
1250 Current.getNextNonComment()->is(tok::string_literal)) ||
1251 (Current.TokenText.find("\\\n") != StringRef::npos)))
1252 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001253
Daniel Jaspere8b10d32013-07-26 16:56:36 +00001254 if (!Style.BreakBeforeBinaryOperators) {
1255 // If we need to break somewhere inside the LHS of a binary expression, we
1256 // should also break after the operator. Otherwise, the formatting would
1257 // hide the operator precedence, e.g. in:
1258 // if (aaaaaaaaaaaaaa ==
1259 // bbbbbbbbbbbbbb && c) {..
1260 // For comparisons, we only apply this rule, if the LHS is a binary
1261 // expression itself as otherwise, the line breaks seem superfluous.
1262 // We need special cases for ">>" which we have split into two ">" while
1263 // lexing in order to make template parsing easier.
1264 //
1265 // FIXME: We'll need something similar for styles that break before binary
1266 // operators.
1267 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1268 Previous.getPrecedence() == prec::Equality) &&
1269 Previous.Previous && Previous.Previous->Type !=
1270 TT_BinaryOperator; // For >>.
1271 bool LHSIsBinaryExpr =
1272 Previous.Previous && Previous.Previous->FakeRParens > 0;
1273 if (Previous.Type == TT_BinaryOperator &&
1274 (!IsComparison || LHSIsBinaryExpr) &&
1275 Current.Type != TT_BinaryOperator && // For >>.
1276 !Current.isTrailingComment() &&
1277 !Previous.isOneOf(tok::lessless, tok::question) &&
1278 Previous.getPrecedence() != prec::Assignment &&
1279 State.Stack.back().BreakBeforeParameter)
1280 return true;
1281 }
Daniel Jasper11e13802013-05-08 14:12:04 +00001282
Daniel Jaspera0740f52013-07-12 15:14:05 +00001283 // Same as above, but for the first "<<" operator.
1284 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1285 State.Stack.back().FirstLessLess == 0)
1286 return true;
1287
Daniel Jasper11e13802013-05-08 14:12:04 +00001288 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1289 // out whether it is the first parameter. Clean this up.
1290 if (Current.Type == TT_ObjCSelectorName &&
1291 Current.LongestObjCSelectorName == 0 &&
1292 State.Stack.back().BreakBeforeParameter)
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001293 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001294 if ((Current.Type == TT_CtorInitializerColon ||
1295 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper923ebef2013-03-14 13:45:21 +00001296 return true;
Daniel Jasper11e13802013-05-08 14:12:04 +00001297
Daniel Jasper6561f6a2013-07-09 07:43:55 +00001298 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1299 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1300 State.ParenLevel == 0)
Daniel Jasper33f4b902013-05-15 09:35:08 +00001301 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001302 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001303 }
1304
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001305 // Returns the total number of columns required for the remaining tokens.
1306 unsigned getRemainingLength(const LineState &State) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001307 if (State.NextToken && State.NextToken->Previous)
1308 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001309 return 0;
1310 }
1311
Daniel Jasperbac016b2012-12-03 18:12:45 +00001312 FormatStyle Style;
1313 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001314 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001315 const unsigned FirstIndent;
Manuel Klimekb3987012013-05-29 14:47:47 +00001316 const FormatToken *RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001317 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001318
1319 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1320 QueueType Queue;
1321 // Increasing count of \c StateNode items we have created. This is used
1322 // to create a deterministic order independent of the container.
1323 unsigned Count;
Alexander Kornienko00895102013-06-05 14:09:10 +00001324 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001325 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001326};
1327
Manuel Klimek96e888b2013-05-28 11:55:06 +00001328class FormatTokenLexer {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001329public:
Alexander Kornienko00895102013-06-05 14:09:10 +00001330 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1331 encoding::Encoding Encoding)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001332 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienko00895102013-06-05 14:09:10 +00001333 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1334 Encoding(Encoding) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001335 Lex.SetKeepWhitespaceMode(true);
1336 }
1337
Manuel Klimek96e888b2013-05-28 11:55:06 +00001338 ArrayRef<FormatToken *> lex() {
1339 assert(Tokens.empty());
1340 do {
1341 Tokens.push_back(getNextToken());
1342 } while (Tokens.back()->Tok.isNot(tok::eof));
1343 return Tokens;
1344 }
1345
1346 IdentifierTable &getIdentTable() { return IdentTable; }
1347
1348private:
1349 FormatToken *getNextToken() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001350 if (GreaterStashed) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001351 // Create a synthesized second '>' token.
1352 Token Greater = FormatTok->Tok;
1353 FormatTok = new (Allocator.Allocate()) FormatToken;
1354 FormatTok->Tok = Greater;
Manuel Klimekad3094b2013-05-23 10:56:37 +00001355 SourceLocation GreaterLocation =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001356 FormatTok->Tok.getLocation().getLocWithOffset(1);
1357 FormatTok->WhitespaceRange =
1358 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001359 FormatTok->TokenText = ">";
Alexander Kornienko00895102013-06-05 14:09:10 +00001360 FormatTok->CodePointCount = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001361 GreaterStashed = false;
1362 return FormatTok;
1363 }
1364
Manuel Klimek96e888b2013-05-28 11:55:06 +00001365 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper561211d2013-07-16 20:28:33 +00001366 readRawToken(*FormatTok);
Manuel Klimekde008c02013-05-27 15:23:34 +00001367 SourceLocation WhitespaceStart =
Manuel Klimek96e888b2013-05-28 11:55:06 +00001368 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimekad3094b2013-05-23 10:56:37 +00001369 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek96e888b2013-05-28 11:55:06 +00001370 FormatTok->IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001371
1372 // Consume and record whitespace until we find a significant token.
Manuel Klimekde008c02013-05-27 15:23:34 +00001373 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001374 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001375 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001376 if (Newlines > 0)
Daniel Jasper561211d2013-07-16 20:28:33 +00001377 FormatTok->LastNewlineOffset =
1378 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001379 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper561211d2013-07-16 20:28:33 +00001380 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek96e888b2013-05-28 11:55:06 +00001381 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1382 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001383
Daniel Jasper561211d2013-07-16 20:28:33 +00001384 readRawToken(*FormatTok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001385 }
Manuel Klimek95419382013-01-07 07:56:50 +00001386
Manuel Klimekd4397b92013-01-04 23:34:14 +00001387 // In case the token starts with escaped newlines, we want to
1388 // take them into account as whitespace - this pattern is quite frequent
1389 // in macro definitions.
1390 // FIXME: What do we want to do with other escaped spaces, and escaped
1391 // spaces or newlines in the middle of tokens?
1392 // FIXME: Add a more explicit test.
Daniel Jasper561211d2013-07-16 20:28:33 +00001393 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1394 FormatTok->TokenText[1] == '\n') {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001395 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimekad3094b2013-05-23 10:56:37 +00001396 WhitespaceLength += 2;
Daniel Jasper561211d2013-07-16 20:28:33 +00001397 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001398 }
1399
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001400 TrailingWhitespace = 0;
1401 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001402 StringRef UntrimmedText = FormatTok->TokenText;
1403 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1404 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001405 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper561211d2013-07-16 20:28:33 +00001406 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001407 FormatTok->Tok.setIdentifierInfo(&Info);
1408 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001409 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek96e888b2013-05-28 11:55:06 +00001410 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper561211d2013-07-16 20:28:33 +00001411 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001412 GreaterStashed = true;
1413 }
1414
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001415 // Now FormatTok is the next non-whitespace token.
Daniel Jasper561211d2013-07-16 20:28:33 +00001416 FormatTok->CodePointCount =
1417 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienko00895102013-06-05 14:09:10 +00001418
Manuel Klimek96e888b2013-05-28 11:55:06 +00001419 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001420 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001421 return FormatTok;
1422 }
1423
Manuel Klimek96e888b2013-05-28 11:55:06 +00001424 FormatToken *FormatTok;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001425 bool GreaterStashed;
Manuel Klimekde008c02013-05-27 15:23:34 +00001426 unsigned TrailingWhitespace;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001427 Lexer &Lex;
1428 SourceManager &SourceMgr;
1429 IdentifierTable IdentTable;
Alexander Kornienko00895102013-06-05 14:09:10 +00001430 encoding::Encoding Encoding;
Manuel Klimek96e888b2013-05-28 11:55:06 +00001431 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1432 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001433
Daniel Jasper561211d2013-07-16 20:28:33 +00001434 void readRawToken(FormatToken &Tok) {
1435 Lex.LexFromRawLexer(Tok.Tok);
1436 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1437 Tok.Tok.getLength());
1438
1439 // For formatting, treat unterminated string literals like normal string
1440 // literals.
1441 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1442 Tok.TokenText[0] == '"') {
1443 Tok.Tok.setKind(tok::string_literal);
1444 Tok.IsUnterminatedLiteral = true;
1445 }
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001446 }
1447};
1448
Daniel Jasperbac016b2012-12-03 18:12:45 +00001449class Formatter : public UnwrappedLineConsumer {
1450public:
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001451 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001452 const std::vector<CharSourceRange> &Ranges)
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001453 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko00895102013-06-05 14:09:10 +00001454 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1455 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasper9637dda2013-07-15 14:33:14 +00001456 DEBUG(llvm::dbgs() << "File encoding: "
1457 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1458 : "unknown")
1459 << "\n");
Alexander Kornienko00895102013-06-05 14:09:10 +00001460 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001461
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001462 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001463
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001464 tooling::Replacements format() {
Alexander Kornienko00895102013-06-05 14:09:10 +00001465 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek96e888b2013-05-28 11:55:06 +00001466
1467 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001468 bool StructuralError = Parser.parse();
Alexander Kornienko00895102013-06-05 14:09:10 +00001469 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001470 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1471 Annotator.annotate(AnnotatedLines[i]);
1472 }
1473 deriveLocalStyle();
1474 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1475 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1476 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001477
1478 // Adapt level to the next line if this is a comment.
1479 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001480 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001481 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001482 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001483 !AnnotatedLines[i].First->Next)
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001484 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasper5999f762013-04-09 17:46:55 +00001485 else
Daniel Jasper2a409b62013-07-08 14:34:09 +00001486 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1487 ? &AnnotatedLines[i]
1488 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001489 }
1490
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001491 std::vector<int> IndentForLevel;
1492 bool PreviousLineWasTouched = false;
Manuel Klimekb3987012013-05-29 14:47:47 +00001493 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001494 bool FormatPPDirective = false;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001495 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1496 E = AnnotatedLines.end();
1497 I != E; ++I) {
1498 const AnnotatedLine &TheLine = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001499 const FormatToken *FirstTok = TheLine.First;
1500 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001501
1502 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001503 if (FirstTok->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001504 FormatPPDirective = false;
1505 if (!FormatPPDirective && TheLine.InPPDirective &&
1506 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1507 FormatPPDirective = true;
1508
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001509 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001510 while (IndentForLevel.size() <= TheLine.Level)
1511 IndentForLevel.push_back(-1);
1512 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001513 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1514 if (static_cast<int>(Indent) + Offset >= 0)
1515 Indent += Offset;
1516 tryFitMultipleLinesInOne(Indent, I, E);
1517
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001518 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimekb3987012013-05-29 14:47:47 +00001519 if (TheLine.First->is(tok::eof)) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001520 if (PreviousLineWasTouched) {
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001521 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001522 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001523 /*TargetColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001524 }
1525 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001526 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001527 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001528 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek67d080d2013-04-12 14:13:36 +00001529 // Insert a break even if there is a structural error in case where
1530 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001531 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001532 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001533 TheLine.InPPDirective);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001534 } else {
1535 Indent = LevelIndent =
Manuel Klimekdcb3f2a2013-05-28 13:42:28 +00001536 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1537 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001538 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001539 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001540 TheLine.First, Whitespaces, Encoding,
1541 BinPackInconclusiveFunctions);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001542 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001543 IndentForLevel[TheLine.Level] = LevelIndent;
1544 PreviousLineWasTouched = true;
1545 } else {
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001546 // Format the first token if necessary, and notify the WhitespaceManager
1547 // about the unchanged whitespace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001548 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1549 Tok = Tok->Next) {
1550 if (Tok == TheLine.First &&
1551 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1552 unsigned LevelIndent =
1553 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001554 // Remove trailing whitespace of the previous line if it was
1555 // touched.
1556 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1557 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1558 TheLine.InPPDirective);
1559 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001560 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001561 }
Daniel Jasper1fb8d882013-05-14 09:30:02 +00001562
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001563 if (static_cast<int>(LevelIndent) - Offset >= 0)
1564 LevelIndent -= Offset;
1565 if (Tok->isNot(tok::comment))
1566 IndentForLevel[TheLine.Level] = LevelIndent;
1567 } else {
Manuel Klimekb3987012013-05-29 14:47:47 +00001568 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001569 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001570 }
1571 // If we did not reformat this unwrapped line, the column at the end of
1572 // the last token is unchanged - thus, we can calculate the end of the
1573 // last token.
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001574 PreviousLineWasTouched = false;
1575 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001576 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001577 }
1578 return Whitespaces.generateReplacements();
1579 }
1580
1581private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001582 void deriveLocalStyle() {
1583 unsigned CountBoundToVariable = 0;
1584 unsigned CountBoundToType = 0;
1585 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001586 bool HasBinPackedFunction = false;
1587 bool HasOnePerLineFunction = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001588 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001589 if (!AnnotatedLines[i].First->Next)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001590 continue;
Manuel Klimekb3987012013-05-29 14:47:47 +00001591 FormatToken *Tok = AnnotatedLines[i].First->Next;
1592 while (Tok->Next) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001593 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001594 bool SpacesBefore =
1595 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1596 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1597 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001598 if (SpacesBefore && !SpacesAfter)
1599 ++CountBoundToVariable;
1600 else if (!SpacesBefore && SpacesAfter)
1601 ++CountBoundToType;
1602 }
1603
Daniel Jasper29f123b2013-02-08 15:28:42 +00001604 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001605 Tok->Previous->Type == TT_TemplateCloser &&
1606 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001607 HasCpp03IncompatibleFormat = true;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001608
1609 if (Tok->PackingKind == PPK_BinPacked)
1610 HasBinPackedFunction = true;
1611 if (Tok->PackingKind == PPK_OnePerLine)
1612 HasOnePerLineFunction = true;
1613
Manuel Klimekb3987012013-05-29 14:47:47 +00001614 Tok = Tok->Next;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001615 }
1616 }
1617 if (Style.DerivePointerBinding) {
1618 if (CountBoundToType > CountBoundToVariable)
1619 Style.PointerBindsToType = true;
1620 else if (CountBoundToType < CountBoundToVariable)
1621 Style.PointerBindsToType = false;
1622 }
1623 if (Style.Standard == FormatStyle::LS_Auto) {
1624 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1625 : FormatStyle::LS_Cpp03;
1626 }
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001627 BinPackInconclusiveFunctions =
1628 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001629 }
1630
Manuel Klimek547d5db2013-02-08 17:38:27 +00001631 /// \brief Get the indent of \p Level from \p IndentForLevel.
1632 ///
1633 /// \p IndentForLevel must contain the indent for the level \c l
1634 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1635 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001636 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001637 if (IndentForLevel[Level] != -1)
1638 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001639 if (Level == 0)
1640 return 0;
Manuel Klimek07a64ec2013-05-13 08:42:42 +00001641 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001642 }
1643
1644 /// \brief Get the offset of the line relatively to the level.
1645 ///
1646 /// For example, 'public:' labels in classes are offset by 1 or 2
1647 /// characters to the left from their level.
Manuel Klimekb3987012013-05-29 14:47:47 +00001648 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001649 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001650 return Style.AccessModifierOffset;
1651 return 0;
1652 }
1653
Manuel Klimek517e8942013-01-11 17:54:10 +00001654 /// \brief Tries to merge lines into one.
1655 ///
1656 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1657 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001658 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001659 std::vector<AnnotatedLine>::iterator &I,
1660 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001661 // We can never merge stuff if there are trailing line comments.
1662 if (I->Last->Type == TT_LineComment)
1663 return;
1664
Daniel Jaspere05dc6d2013-07-24 13:10:59 +00001665 if (Indent > Style.ColumnLimit)
1666 return;
1667
Daniel Jaspera4d46212013-02-28 11:05:57 +00001668 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001669 // If we already exceed the column limit, we set 'Limit' to 0. The different
1670 // tryMerge..() functions can then decide whether to still do merging.
1671 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001672
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001673 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001674 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001675
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001676 if (I->Last->is(tok::l_brace)) {
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001677 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001678 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001679 I->First->is(tok::kw_if)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001680 tryMergeSimpleControlStatement(I, E, Limit);
1681 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001682 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001683 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimekb3987012013-05-29 14:47:47 +00001684 } else if (I->InPPDirective &&
1685 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001686 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001687 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001688 }
1689
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001690 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1691 std::vector<AnnotatedLine>::iterator E,
1692 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001693 if (Limit == 0)
1694 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001695 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001696 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001697 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001698 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001699 !(I + 2)->First->HasUnescapedNewline)
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001700 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001701 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001702 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001703 join(Line, *(++I));
1704 }
1705
Daniel Jasperf11bbb92013-05-16 12:12:21 +00001706 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1707 std::vector<AnnotatedLine>::iterator E,
1708 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001709 if (Limit == 0)
1710 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001711 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimekb3987012013-05-29 14:47:47 +00001712 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimek4c128122013-01-18 14:46:43 +00001713 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001714 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001715 if (Line.Last->isNot(tok::r_paren))
1716 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001717 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001718 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001719 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1720 tok::kw_while) ||
1721 (I + 1)->First->Type == TT_LineComment)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001722 return;
1723 // Only inline simple if's (no nested if or else).
Manuel Klimekb3987012013-05-29 14:47:47 +00001724 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1725 (I + 2)->First->is(tok::kw_else))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001726 return;
1727 join(Line, *(++I));
1728 }
1729
1730 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001731 std::vector<AnnotatedLine>::iterator E,
1732 unsigned Limit) {
Daniel Jasper5be59ba2013-05-15 14:09:55 +00001733 // No merging if the brace already is on the next line.
1734 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1735 return;
1736
Manuel Klimek517e8942013-01-11 17:54:10 +00001737 // First, check that the current line allows merging. This is the case if
1738 // we're not in a control flow statement and the last token is an opening
1739 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001740 AnnotatedLine &Line = *I;
Manuel Klimekb3987012013-05-29 14:47:47 +00001741 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1742 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001743 tok::kw_for,
Manuel Klimekb3987012013-05-29 14:47:47 +00001744 // This gets rid of all ObjC @ keywords and methods.
1745 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001746 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001747
Manuel Klimekb3987012013-05-29 14:47:47 +00001748 FormatToken *Tok = (I + 1)->First;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001749 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001750 (Tok->getNextNonComment() == NULL ||
1751 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001752 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001753 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001754 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001755 join(Line, *(I + 1));
1756 I += 1;
Daniel Jasper8893b8a2013-05-31 14:56:20 +00001757 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001758 // Check that we still have three lines and they fit into the limit.
1759 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1760 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001761 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001762
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001763 // Second, check that the next line does not contain any braces - if it
1764 // does, readability declines when putting it into a single line.
1765 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1766 return;
1767 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001768 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001769 return;
Manuel Klimekb3987012013-05-29 14:47:47 +00001770 Tok = Tok->Next;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001771 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001772
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001773 // Last, check that the third line contains a single closing brace.
Manuel Klimekb3987012013-05-29 14:47:47 +00001774 Tok = (I + 2)->First;
Alexander Kornienko0bdc6432013-07-04 14:47:51 +00001775 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001776 Tok->MustBreakBefore)
1777 return;
1778
1779 join(Line, *(I + 1));
1780 join(Line, *(I + 2));
1781 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001782 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001783 }
1784
1785 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1786 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001787 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1788 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001789 }
1790
Daniel Jasper995e8202013-01-14 13:08:07 +00001791 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001792 assert(!A.Last->Next);
1793 assert(!B.First->Previous);
1794 A.Last->Next = B.First;
1795 B.First->Previous = A.Last;
1796 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1797 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1798 Tok->TotalLength += LengthA;
1799 A.Last = Tok;
Daniel Jasper995e8202013-01-14 13:08:07 +00001800 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001801 }
1802
Daniel Jasper6f21a982013-03-13 07:49:51 +00001803 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001804 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1805 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1806 Ranges[i].getBegin()) &&
1807 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1808 Range.getBegin()))
1809 return true;
1810 }
1811 return false;
1812 }
1813
1814 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001815 const FormatToken *First = TheLine.First;
1816 const FormatToken *Last = TheLine.Last;
Daniel Jasper84f5ddf2013-05-14 10:31:09 +00001817 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001818 First->WhitespaceRange.getBegin().getLocWithOffset(
1819 First->LastNewlineOffset),
Alexander Kornienko54e6c9d2013-06-07 17:45:07 +00001820 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf3023542013-03-07 20:50:00 +00001821 return touchesRanges(LineRange);
1822 }
1823
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001824 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1825 std::vector<AnnotatedLine>::iterator E) {
1826 for (; I != E; ++I) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001827 if (I->First->HasUnescapedNewline)
Daniel Jasper89b3a7f2013-05-10 13:00:49 +00001828 return false;
1829 if (touchesLine(*I))
1830 return true;
1831 }
1832 return false;
1833 }
1834
Daniel Jasperf3023542013-03-07 20:50:00 +00001835 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimekb3987012013-05-29 14:47:47 +00001836 const FormatToken *First = TheLine.First;
Daniel Jasperf3023542013-03-07 20:50:00 +00001837 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimekad3094b2013-05-23 10:56:37 +00001838 First->WhitespaceRange.getBegin(),
1839 First->WhitespaceRange.getBegin().getLocWithOffset(
1840 First->LastNewlineOffset));
Daniel Jasperf3023542013-03-07 20:50:00 +00001841 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001842 }
1843
1844 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001845 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001846 }
1847
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001848 /// \brief Add a new line and the required indent before the first Token
1849 /// of the \c UnwrappedLine if there was no structural parsing error.
1850 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb3987012013-05-29 14:47:47 +00001851 void formatFirstToken(const FormatToken &RootToken,
1852 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001853 bool InPPDirective) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001854 unsigned Newlines =
Manuel Klimekb3987012013-05-29 14:47:47 +00001855 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper15f33f02013-06-03 16:16:41 +00001856 // Remove empty lines before "}" where applicable.
1857 if (RootToken.is(tok::r_brace) &&
1858 (!RootToken.Next ||
1859 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1860 Newlines = std::min(Newlines, 1u);
Manuel Klimekb3987012013-05-29 14:47:47 +00001861 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001862 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001863
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001864 // Insert extra new line before access specifiers.
1865 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimekb3987012013-05-29 14:47:47 +00001866 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimeke573c3f2013-05-22 12:51:29 +00001867 ++Newlines;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001868
Manuel Klimekb3987012013-05-29 14:47:47 +00001869 Whitespaces.replaceWhitespace(
1870 RootToken, Newlines, Indent, Indent,
1871 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001872 }
1873
Daniel Jasperbac016b2012-12-03 18:12:45 +00001874 FormatStyle Style;
1875 Lexer &Lex;
1876 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001877 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001878 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001879 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko00895102013-06-05 14:09:10 +00001880
1881 encoding::Encoding Encoding;
Daniel Jasperc7bd68f2013-07-10 14:02:49 +00001882 bool BinPackInconclusiveFunctions;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001883};
1884
Craig Topper83f81d72013-06-30 22:29:28 +00001885} // end anonymous namespace
1886
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001887tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1888 SourceManager &SourceMgr,
Daniel Jaspercaf42a32013-05-15 08:14:19 +00001889 std::vector<CharSourceRange> Ranges) {
1890 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001891 return formatter.format();
1892}
1893
Daniel Jasper8a999452013-05-16 10:40:07 +00001894tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1895 std::vector<tooling::Range> Ranges,
1896 StringRef FileName) {
1897 FileManager Files((FileSystemOptions()));
1898 DiagnosticsEngine Diagnostics(
1899 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1900 new DiagnosticOptions);
1901 SourceManager SourceMgr(Diagnostics, Files);
1902 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1903 const clang::FileEntry *Entry =
1904 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1905 SourceMgr.overrideFileContents(Entry, Buf);
1906 FileID ID =
1907 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001908 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1909 getFormattingLangOpts(Style.Standard));
Daniel Jasper8a999452013-05-16 10:40:07 +00001910 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1911 std::vector<CharSourceRange> CharRanges;
1912 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1913 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1914 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1915 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1916 }
1917 return reformat(Style, Lex, SourceMgr, CharRanges);
1918}
1919
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001920LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasper46ef8522013-01-10 13:08:12 +00001921 LangOptions LangOpts;
1922 LangOpts.CPlusPlus = 1;
Alexander Kornienkoa1753f42013-06-28 12:51:24 +00001923 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001924 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001925 LangOpts.Bool = 1;
1926 LangOpts.ObjC1 = 1;
1927 LangOpts.ObjC2 = 1;
1928 return LangOpts;
1929}
1930
Daniel Jaspercd162382013-01-07 13:26:07 +00001931} // namespace format
1932} // namespace clang