blob: ec1497c87f4cd7d06d64ebe0289c01126e6cc992 [file] [log] [blame]
Daniel Jasperf7935112012-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 Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Daniel Jasperec04c0d2013-05-16 10:40:07 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000026#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000027#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000029#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000030#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Alexander Kornienkod6538332013-05-07 15:32:14 +000034namespace llvm {
35namespace yaml {
36template <>
37struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
Manuel Klimeka8eb9142013-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 Jasper12f9d8e2013-05-14 09:30:02 +000046template <>
Manuel Klimeka8eb9142013-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);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +000053 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman);
Alexander Kornienkod6538332013-05-07 15:32:14 +000054 }
55};
56
Daniel Jasper65ee3472013-07-31 23:16:02 +000057template <>
58struct ScalarEnumerationTraits<
59 clang::format::FormatStyle::NamespaceIndentationKind> {
60 static void
61 enumeration(IO &IO,
62 clang::format::FormatStyle::NamespaceIndentationKind &Value) {
63 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None);
64 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner);
65 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All);
66 }
67};
68
Alexander Kornienkod6538332013-05-07 15:32:14 +000069template <> struct MappingTraits<clang::format::FormatStyle> {
70 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000071 if (IO.outputting()) {
72 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
73 ArrayRef<StringRef> Styles(StylesArray);
74 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
75 StringRef StyleName(Styles[i]);
Alexander Kornienko006b5c82013-05-19 00:53:30 +000076 clang::format::FormatStyle PredefinedStyle;
77 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
78 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000079 IO.mapOptional("# BasedOnStyle", StyleName);
80 break;
81 }
82 }
83 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000084 StringRef BasedOnStyle;
85 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000086 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-05-19 00:53:30 +000087 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
88 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
89 return;
90 }
Alexander Kornienkod6538332013-05-07 15:32:14 +000091 }
92
93 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
Daniel Jaspercdaffa42013-08-13 10:58:30 +000094 IO.mapOptional("ConstructorInitializerIndentWidth",
95 Style.ConstructorInitializerIndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +000096 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
Daniel Jasper552f4a72013-07-31 23:55:15 +000097 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
Alexander Kornienkod6538332013-05-07 15:32:14 +000098 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
99 Style.AllowAllParametersOfDeclarationOnNextLine);
100 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
101 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +0000102 IO.mapOptional("AllowShortLoopsOnASingleLine",
103 Style.AllowShortLoopsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000104 IO.mapOptional("AlwaysBreakTemplateDeclarations",
105 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +0000106 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
107 Style.AlwaysBreakBeforeMultilineStrings);
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000108 IO.mapOptional("BreakBeforeBinaryOperators",
109 Style.BreakBeforeBinaryOperators);
110 IO.mapOptional("BreakConstructorInitializersBeforeComma",
111 Style.BreakConstructorInitializersBeforeComma);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000112 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
113 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
114 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
115 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
116 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000117 IO.mapOptional("ExperimentalAutoDetectBinPacking",
118 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000119 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
120 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000121 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000122 IO.mapOptional("ObjCSpaceBeforeProtocolList",
123 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000124 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
125 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000126 IO.mapOptional("PenaltyBreakFirstLessLess",
127 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000128 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
129 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
130 Style.PenaltyReturnTypeOnItsOwnLine);
131 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
132 IO.mapOptional("SpacesBeforeTrailingComments",
133 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000134 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000135 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000136 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000137 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000138 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000139 IO.mapOptional("IndentFunctionDeclarationAfterType",
140 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000141 }
142};
143}
144}
145
Daniel Jasperf7935112012-12-03 18:12:45 +0000146namespace clang {
147namespace format {
148
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000149void setDefaultPenalties(FormatStyle &Style) {
150 Style.PenaltyBreakComment = 45;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000151 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000152 Style.PenaltyBreakString = 1000;
153 Style.PenaltyExcessCharacter = 1000000;
154}
155
Daniel Jasperf7935112012-12-03 18:12:45 +0000156FormatStyle getLLVMStyle() {
157 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000158 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000159 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000160 LLVMStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000161 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000162 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000163 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000164 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000165 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000166 LLVMStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000167 LLVMStyle.BreakBeforeBinaryOperators = false;
168 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
169 LLVMStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000170 LLVMStyle.ColumnLimit = 80;
171 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000172 LLVMStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000173 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000174 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000175 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000176 LLVMStyle.IndentCaseLabels = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000177 LLVMStyle.IndentFunctionDeclarationAfterType = false;
178 LLVMStyle.IndentWidth = 2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000179 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000180 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000181 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000182 LLVMStyle.PointerBindsToType = false;
183 LLVMStyle.SpacesBeforeTrailingComments = 1;
184 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000185 LLVMStyle.UseTab = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000186
187 setDefaultPenalties(LLVMStyle);
188 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
189
Daniel Jasperf7935112012-12-03 18:12:45 +0000190 return LLVMStyle;
191}
192
193FormatStyle getGoogleStyle() {
194 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000195 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000196 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000197 GoogleStyle.AlignTrailingComments = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000198 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000199 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000200 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000201 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000202 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000203 GoogleStyle.BinPackParameters = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000204 GoogleStyle.BreakBeforeBinaryOperators = false;
205 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
206 GoogleStyle.BreakConstructorInitializersBeforeComma = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000207 GoogleStyle.ColumnLimit = 80;
208 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000209 GoogleStyle.ConstructorInitializerIndentWidth = 4;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000210 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000211 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000212 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000213 GoogleStyle.IndentCaseLabels = true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000214 GoogleStyle.IndentFunctionDeclarationAfterType = true;
215 GoogleStyle.IndentWidth = 2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000216 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000217 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None;
Nico Webera6087752013-01-10 20:12:55 +0000218 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000219 GoogleStyle.PointerBindsToType = true;
220 GoogleStyle.SpacesBeforeTrailingComments = 2;
221 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000222 GoogleStyle.UseTab = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000223
224 setDefaultPenalties(GoogleStyle);
225 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
226
Daniel Jasperf7935112012-12-03 18:12:45 +0000227 return GoogleStyle;
228}
229
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000230FormatStyle getChromiumStyle() {
231 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000232 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000233 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000234 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000235 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000236 ChromiumStyle.DerivePointerBinding = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000237 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000238 return ChromiumStyle;
239}
240
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000241FormatStyle getMozillaStyle() {
242 FormatStyle MozillaStyle = getLLVMStyle();
243 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
244 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
245 MozillaStyle.DerivePointerBinding = true;
246 MozillaStyle.IndentCaseLabels = true;
247 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
248 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
249 MozillaStyle.PointerBindsToType = true;
250 return MozillaStyle;
251}
252
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000253FormatStyle getWebKitStyle() {
254 FormatStyle Style = getLLVMStyle();
Daniel Jasper65ee3472013-07-31 23:16:02 +0000255 Style.AccessModifierOffset = -4;
Daniel Jasper552f4a72013-07-31 23:55:15 +0000256 Style.AlignTrailingComments = false;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000257 Style.BreakBeforeBinaryOperators = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000258 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000259 Style.BreakConstructorInitializersBeforeComma = true;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000260 Style.ColumnLimit = 0;
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000261 Style.IndentWidth = 4;
Daniel Jasper65ee3472013-07-31 23:16:02 +0000262 Style.NamespaceIndentation = FormatStyle::NI_Inner;
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000263 Style.PointerBindsToType = true;
264 return Style;
265}
266
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000267bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000268 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000269 *Style = getLLVMStyle();
270 else if (Name.equals_lower("chromium"))
271 *Style = getChromiumStyle();
272 else if (Name.equals_lower("mozilla"))
273 *Style = getMozillaStyle();
274 else if (Name.equals_lower("google"))
275 *Style = getGoogleStyle();
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000276 else if (Name.equals_lower("webkit"))
277 *Style = getWebKitStyle();
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000278 else
279 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000280
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000281 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000282}
283
284llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000285 if (Text.trim().empty())
286 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000287 llvm::yaml::Input Input(Text);
288 Input >> *Style;
289 return Input.error();
290}
291
292std::string configurationAsText(const FormatStyle &Style) {
293 std::string Text;
294 llvm::raw_string_ostream Stream(Text);
295 llvm::yaml::Output Output(Stream);
296 // We use the same mapping method for input and output, so we need a non-const
297 // reference here.
298 FormatStyle NonConstStyle = Style;
299 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000300 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000301}
302
Daniel Jasperacc33662013-02-08 08:22:00 +0000303// Returns the length of everything up to the first possible line break after
304// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000305static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000306 if (Tok.MatchingParen == NULL)
307 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000308 FormatToken *End = Tok.MatchingParen;
309 while (End->Next && !End->Next->CanBreakBefore) {
310 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000311 }
312 return End->TotalLength - Tok.TotalLength + 1;
313}
314
Craig Topperaf35e852013-06-30 22:29:28 +0000315namespace {
316
Daniel Jasperf7935112012-12-03 18:12:45 +0000317class UnwrappedLineFormatter {
318public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000319 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000320 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000321 const FormatToken *RootToken,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000322 WhitespaceManager &Whitespaces,
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000323 encoding::Encoding Encoding,
324 bool BinPackInconclusiveFunctions)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000325 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000326 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000327 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
328 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000329
Manuel Klimek1abf7892013-01-04 23:34:14 +0000330 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000331 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000332 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000333 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000334 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000335 State.NextToken = RootToken;
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000336 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
337 /*AvoidBinPacking=*/false,
338 /*NoLineBreak=*/false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000339 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000340 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000341 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000342 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000343 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000344 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000345
346 // The first token has already been indented and thus consumed.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000347 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000348
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000349 if (Style.ColumnLimit == 0) {
350 formatWithoutColumnLimit(State);
351 return;
352 }
353
Daniel Jasper4b866272013-02-01 11:00:45 +0000354 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000355 unsigned ColumnLimit = Style.ColumnLimit;
356 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000357 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000358 ColumnLimit = getColumnLimit();
359 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000360 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000361 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000362 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000363 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000364
Daniel Jasperacc33662013-02-08 08:22:00 +0000365 // If the ObjC method declaration does not fit on a line, we should format
366 // it with one arg per line.
367 if (Line.Type == LT_ObjCMethodDecl)
368 State.Stack.back().BreakBeforeParameter = true;
369
Daniel Jasper4b866272013-02-01 11:00:45 +0000370 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000371 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 }
373
374private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000375 void DebugTokenState(const FormatToken &FormatTok) {
376 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000377 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000378 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000379 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000380 }
381
Daniel Jasper337816e2013-01-11 10:22:12 +0000382 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000383 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000384 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000385 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
386 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000387 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000388 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000389 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
390 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000391
Daniel Jasperf7935112012-12-03 18:12:45 +0000392 /// \brief The position to which a specific parenthesis level needs to be
393 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000394 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000395
Daniel Jaspere9de2602012-12-06 09:56:08 +0000396 /// \brief The position of the last space on each level.
397 ///
398 /// Used e.g. to break like:
399 /// functionCall(Parameter, otherCall(
400 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000401 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000402
Daniel Jaspere9de2602012-12-06 09:56:08 +0000403 /// \brief The position the first "<<" operator encountered on each level.
404 ///
405 /// Used to align "<<" operators. 0 if no such operator has been encountered
406 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000407 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000408
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000409 /// \brief Whether a newline needs to be inserted before the block's closing
410 /// brace.
411 ///
412 /// We only want to insert a newline before the closing brace if there also
413 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000414 bool BreakBeforeClosingBrace;
415
Daniel Jasperca6623b2013-01-28 12:45:14 +0000416 /// \brief The column of a \c ? in a conditional expression;
417 unsigned QuestionColumn;
418
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000419 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
420 /// lines, in this context.
421 bool AvoidBinPacking;
422
423 /// \brief Break after the next comma (or all the commas in this context if
424 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000425 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000426
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000427 /// \brief Line breaking in this context would break a formatting rule.
428 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000429
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000430 /// \brief The position of the colon in an ObjC method declaration/call.
431 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000432
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000433 /// \brief The start of the most recent function in a builder-type call.
434 unsigned StartOfFunctionCall;
435
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000436 /// \brief Contains the start of array subscript expressions, so that they
437 /// can be aligned.
438 unsigned StartOfArraySubscripts;
439
Daniel Jasperc238c872013-04-02 14:33:13 +0000440 /// \brief If a nested name specifier was broken over multiple lines, this
441 /// contains the start column of the second line. Otherwise 0.
442 unsigned NestedNameSpecifierContinuation;
443
444 /// \brief If a call expression was broken over multiple lines, this
445 /// contains the start column of the second line. Otherwise 0.
446 unsigned CallContinuation;
447
Daniel Jaspera628c982013-04-03 13:36:17 +0000448 /// \brief The column of the first variable name in a variable declaration.
449 ///
450 /// Used to align further variables if necessary.
451 unsigned VariablePos;
452
Daniel Jasperee7539a2013-07-08 14:25:23 +0000453 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000454 ///
Daniel Jasperee7539a2013-07-08 14:25:23 +0000455 /// The first line break in a certain \c ParenState causes extra penalty so
456 /// that clang-format prefers similar breaks, i.e. breaks in the same
457 /// parenthesis.
458 bool ContainsLineBreak;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000459
Daniel Jasper337816e2013-01-11 10:22:12 +0000460 bool operator<(const ParenState &Other) const {
461 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000462 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000463 if (LastSpace != Other.LastSpace)
464 return LastSpace < Other.LastSpace;
465 if (FirstLessLess != Other.FirstLessLess)
466 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000467 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
468 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000469 if (QuestionColumn != Other.QuestionColumn)
470 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000471 if (AvoidBinPacking != Other.AvoidBinPacking)
472 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000473 if (BreakBeforeParameter != Other.BreakBeforeParameter)
474 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000475 if (NoLineBreak != Other.NoLineBreak)
476 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000477 if (ColonPos != Other.ColonPos)
478 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000479 if (StartOfFunctionCall != Other.StartOfFunctionCall)
480 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000481 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
482 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasperc238c872013-04-02 14:33:13 +0000483 if (CallContinuation != Other.CallContinuation)
484 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000485 if (VariablePos != Other.VariablePos)
486 return VariablePos < Other.VariablePos;
Daniel Jasperee7539a2013-07-08 14:25:23 +0000487 if (ContainsLineBreak != Other.ContainsLineBreak)
488 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000489 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000490 }
491 };
492
493 /// \brief The current state when indenting a unwrapped line.
494 ///
495 /// As the indenting tries different combinations this is copied by value.
496 struct LineState {
497 /// \brief The number of used columns in the current line.
498 unsigned Column;
499
500 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000501 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000502
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000503 /// \brief \c true if this line contains a continued for-loop section.
504 bool LineContainsContinuedForLoopSection;
505
Daniel Jasper400adc62013-02-08 15:28:42 +0000506 /// \brief The level of nesting inside (), [], <> and {}.
507 unsigned ParenLevel;
508
Daniel Jasper40c36c52013-02-18 11:05:07 +0000509 /// \brief The \c ParenLevel at the start of this line.
510 unsigned StartOfLineLevel;
511
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000512 /// \brief The lowest \c ParenLevel on the current line.
513 unsigned LowestLevelOnLine;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000514
Manuel Klimek02f640a2013-02-20 15:25:48 +0000515 /// \brief The start column of the string literal, if we're in a string
516 /// literal sequence, 0 otherwise.
517 unsigned StartOfStringLiteral;
518
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 /// \brief A stack keeping track of properties applying to parenthesis
520 /// levels.
521 std::vector<ParenState> Stack;
522
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000523 /// \brief Ignore the stack of \c ParenStates for state comparison.
524 ///
525 /// In long and deeply nested unwrapped lines, the current algorithm can
526 /// be insufficient for finding the best formatting with a reasonable amount
527 /// of time and memory. Setting this flag will effectively lead to the
528 /// algorithm not analyzing some combinations. However, these combinations
529 /// rarely contain the optimal solution: In short, accepting a higher
530 /// penalty early would need to lead to different values in the \c
531 /// ParenState stack (in an otherwise identical state) and these different
532 /// values would need to lead to a significant amount of avoided penalty
533 /// later.
534 ///
535 /// FIXME: Come up with a better algorithm instead.
536 bool IgnoreStackForComparison;
537
Daniel Jasper337816e2013-01-11 10:22:12 +0000538 /// \brief Comparison operator to be able to used \c LineState in \c map.
539 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000540 if (NextToken != Other.NextToken)
541 return NextToken < Other.NextToken;
542 if (Column != Other.Column)
543 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000544 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000545 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000546 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000547 if (ParenLevel != Other.ParenLevel)
548 return ParenLevel < Other.ParenLevel;
549 if (StartOfLineLevel != Other.StartOfLineLevel)
550 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000551 if (LowestLevelOnLine != Other.LowestLevelOnLine)
552 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000553 if (StartOfStringLiteral != Other.StartOfStringLiteral)
554 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000555 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
556 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000557 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 }
559 };
560
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000561 /// \brief Formats the line starting at \p State, simply keeping all of the
562 /// input's line breaking decisions.
563 void formatWithoutColumnLimit(LineState &State) {
564 while (State.NextToken != NULL) {
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000565 bool Newline = mustBreak(State) ||
566 (canBreak(State) && State.NextToken->NewlinesBefore > 0);
Daniel Jasperffefb3d2013-07-24 13:10:59 +0000567 addTokenToState(Newline, /*DryRun=*/false, State);
568 }
569 }
570
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571 /// \brief Appends the next token to \p State and updates information
572 /// necessary for indentation.
573 ///
Nico Weberf579ab32013-06-26 02:42:46 +0000574 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000575 /// line break and necessary indentation otherwise.
576 ///
577 /// If \p DryRun is \c false, also creates and stores the required
578 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000579 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000580 const FormatToken &Current = *State.NextToken;
581 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000582
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000583 // Extra penalty that needs to be added because of the way certain line
584 // breaks are chosen.
585 unsigned ExtraPenalty = 0;
586
Daniel Jasper291f9362013-03-20 15:58:10 +0000587 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000588 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000589 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
590 State.NextToken->WhitespaceRange.getEnd()) -
591 SourceMgr.getSpellingColumnNumber(
592 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000593 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000594 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000595 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000596 }
597
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000598 // If we are continuing an expression, we want to indent an extra 4 spaces.
599 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000600 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000601 if (Newline) {
Daniel Jasper467ddb12013-08-12 12:58:05 +0000602 // Breaking before the first "<<" is generally not desirable if the LHS is
603 // short.
604 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0 &&
605 State.Column <= Style.ColumnLimit / 2)
606 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
607
Daniel Jasperee7539a2013-07-08 14:25:23 +0000608 State.Stack.back().ContainsLineBreak = true;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000609 if (Current.is(tok::r_brace)) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000610 if (Current.BlockKind == BK_BracedInit)
611 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
612 else
Daniel Jasper51efbad2013-07-11 21:27:40 +0000613 State.Column = FirstIndent;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000614 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000615 State.StartOfStringLiteral != 0) {
616 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000617 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000618 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000619 State.Stack.back().FirstLessLess != 0) {
620 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000621 } else if (Current.isOneOf(tok::period, tok::arrow) &&
622 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000623 if (State.Stack.back().CallContinuation == 0) {
624 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000625 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000626 } else {
627 State.Column = State.Stack.back().CallContinuation;
628 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000629 } else if (Current.Type == TT_ConditionalExpr) {
630 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000631 } else if (Previous.is(tok::comma) &&
632 State.Stack.back().VariablePos != 0) {
633 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000634 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6331da02013-07-09 07:43:55 +0000635 ((Current.Type == TT_StartOfName ||
636 Current.is(tok::kw_operator)) &&
637 State.ParenLevel == 0 &&
Manuel Klimek836c2862013-06-21 17:25:42 +0000638 (!Style.IndentFunctionDeclarationAfterType ||
639 Line.StartsDefinition))) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000640 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000641 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000642 if (State.Stack.back().ColonPos > Current.CodePointCount) {
643 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000644 } else {
645 State.Column = State.Stack.back().Indent;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000646 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000647 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000648 } else if (Current.is(tok::l_square) &&
649 Current.Type != TT_ObjCMethodExpr) {
650 if (State.Stack.back().StartOfArraySubscripts != 0)
651 State.Column = State.Stack.back().StartOfArraySubscripts;
652 else
653 State.Column = ContinuationIndent;
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000654 } else if (Current.Type == TT_StartOfName ||
655 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000656 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000657 State.Column = ContinuationIndent;
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000658 } else if (Current.Type == TT_CtorInitializerColon) {
659 State.Column = FirstIndent + Style.ConstructorInitializerIndentWidth;
660 } else if (Current.Type == TT_CtorInitializerComma) {
661 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000662 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000663 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000664 // Ensure that we fall back to indenting 4 spaces instead of just
665 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000666 if (State.Column == FirstIndent)
667 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000668 }
669
Daniel Jasper54a86022013-02-15 11:07:25 +0000670 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000671 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000672 if ((Previous.isOneOf(tok::comma, tok::semi) &&
673 !State.Stack.back().AvoidBinPacking) ||
674 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000675 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000676 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
677 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000678
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000679 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000680 unsigned NewLines = 1;
Alexander Kornienkof370ad92013-06-12 19:04:12 +0000681 if (Current.is(tok::comment))
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000682 NewLines = std::max(
683 NewLines,
684 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000685 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
686 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000687 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000688
Daniel Jasper185de242013-07-11 13:48:16 +0000689 if (!Current.isTrailingComment())
690 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000691 if (Current.isOneOf(tok::arrow, tok::period) &&
692 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000693 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000694 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000695 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000696
697 // Any break on this level means that the parent level has been broken
698 // and we need to avoid bin packing there.
699 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
700 State.Stack[i].BreakBeforeParameter = true;
701 }
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000702 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000703 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000704 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000705 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000706 State.Stack.back().BreakBeforeParameter = true;
707
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000708 // If we break after {, we should also break before the corresponding }.
709 if (Previous.is(tok::l_brace))
710 State.Stack.back().BreakBeforeClosingBrace = true;
711
712 if (State.Stack.back().AvoidBinPacking) {
713 // If we are breaking after '(', '{', '<', this is not bin packing
714 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000715 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
716 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000717 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
718 Line.MustBeDeclaration))
719 State.Stack.back().BreakBeforeParameter = true;
720 }
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000721
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000723 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000724 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000725 State.Stack.back().VariablePos == 0) {
726 State.Stack.back().VariablePos = State.Column;
727 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000728 const FormatToken *Tok = &Previous;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000729 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
730 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000731 if (Tok->SpacesRequiredBefore != 0)
732 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000733 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000734 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000735 if (Previous.PartOfMultiVariableDeclStmt)
736 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
737 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000738
Daniel Jaspereef30492013-02-11 12:36:37 +0000739 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000740
Daniel Jasperf7935112012-12-03 18:12:45 +0000741 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000742 Whitespaces.replaceWhitespace(Current, 0, Spaces,
743 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000744
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000745 if (Current.Type == TT_ObjCSelectorName &&
746 State.Stack.back().ColonPos == 0) {
747 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000748 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000749 State.Stack.back().ColonPos =
750 State.Stack.back().Indent + Current.LongestObjCSelectorName;
751 else
752 State.Stack.back().ColonPos =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000753 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000754 }
755
Daniel Jasperc04baae2013-04-10 09:49:49 +0000756 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000757 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000758 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000759 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
760 State.Stack.back().AvoidBinPacking)
761 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000762
Daniel Jaspere9de2602012-12-06 09:56:08 +0000763 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000764 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000765 // Treat the condition inside an if as if it was a second function
766 // parameter, i.e. let nested calls have an indent of 4.
767 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000768 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000769 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000770 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000771 Previous.Type == TT_ConditionalExpr ||
772 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000773 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000774 Current.FakeLParens.empty()))
775 // Always indent relative to the RHS of the expression unless this is a
776 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000777 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000778 else if (Previous.Type == TT_InheritanceColon)
779 State.Stack.back().Indent = State.Column;
Daniel Jasperbd058882013-07-09 11:57:27 +0000780 else if (Previous.opensScope()) {
781 // If a function has multiple parameters (including a single parameter
Daniel Jasper6cdec7c2013-07-09 14:36:48 +0000782 // that is a binary expression) or a trailing call, indent all
Daniel Jasperbd058882013-07-09 11:57:27 +0000783 // parameters from the opening parenthesis. This avoids confusing
784 // indents like:
785 // OuterFunction(InnerFunctionCall(
786 // ParameterToInnerFunction),
787 // SecondParameterToOuterFunction);
788 bool HasMultipleParameters = !Current.FakeLParens.empty();
789 bool HasTrailingCall = false;
790 if (Previous.MatchingParen) {
791 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
792 if (Next && Next->isOneOf(tok::period, tok::arrow))
793 HasTrailingCall = true;
794 }
795 if (HasMultipleParameters || HasTrailingCall)
796 State.Stack.back().LastSpace = State.Column;
797 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000798 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000799
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000800 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000801 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000802
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000803 /// \brief Mark the next token as consumed in \p State and modify its stacks
804 /// accordingly.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000805 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000806 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000807 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000808
Daniel Jaspereead02b2013-02-14 08:42:54 +0000809 if (Current.Type == TT_InheritanceColon)
810 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000811 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
812 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000813 if (Current.is(tok::l_square) &&
814 State.Stack.back().StartOfArraySubscripts == 0)
815 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000816 if (Current.is(tok::question))
817 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000818 if (!Current.opensScope() && !Current.closesScope())
819 State.LowestLevelOnLine =
820 std::min(State.LowestLevelOnLine, State.ParenLevel);
821 if (Current.isOneOf(tok::period, tok::arrow) &&
822 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
823 State.Stack.back().StartOfFunctionCall =
824 Current.LastInChainOfCalls ? 0
825 : State.Column + Current.CodePointCount;
Daniel Jasper37905f72013-02-21 15:00:29 +0000826 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000827 // Indent 2 from the column, so:
828 // SomeClass::SomeClass()
829 // : First(...), ...
830 // Next(...)
831 // ^ line up here.
Daniel Jaspercdaffa42013-08-13 10:58:30 +0000832 State.Stack.back().Indent =
833 State.Column +
834 (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
Daniel Jasper37905f72013-02-21 15:00:29 +0000835 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
836 State.Stack.back().AvoidBinPacking = true;
837 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000838 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000839
Daniel Jasper6bee6822013-04-08 20:33:42 +0000840 // If return returns a binary expression, align after it.
841 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
842 State.Stack.back().LastSpace = State.Column + 7;
843
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000844 // In ObjC method declaration we align on the ":" of parameters, but we need
845 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000846 if (Current.Type == TT_ObjCMethodSpecifier)
847 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000848
Daniel Jasper400adc62013-02-08 15:28:42 +0000849 // Insert scopes created by fake parenthesis.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000850 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000851 // Don't add extra indentation for the first fake parenthesis after
852 // 'return', assignements or opening <({[. The indentation for these cases
853 // is special cased.
854 bool SkipFirstExtraIndent =
855 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000856 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000857 Previous->getPrecedence() == prec::Assignment));
Craig Topper61ac9062013-07-08 03:55:09 +0000858 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasper6bee6822013-04-08 20:33:42 +0000859 I = Current.FakeLParens.rbegin(),
860 E = Current.FakeLParens.rend();
861 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000862 ParenState NewParenState = State.Stack.back();
Daniel Jasperee7539a2013-07-08 14:25:23 +0000863 NewParenState.ContainsLineBreak = false;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000864 NewParenState.Indent =
865 std::max(std::max(State.Column, NewParenState.Indent),
866 State.Stack.back().LastSpace);
867
868 // Always indent conditional expressions. Never indent expression where
869 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
870 // prec::Assignment) as those have different indentation rules. Indent
871 // other expression, unless the indentation needs to be skipped.
872 if (*I == prec::Conditional ||
Daniel Jaspere33d4af2013-07-26 16:56:36 +0000873 (!SkipFirstExtraIndent && *I > prec::Assignment &&
874 !Style.BreakBeforeBinaryOperators))
Daniel Jasper6bee6822013-04-08 20:33:42 +0000875 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000876 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000877 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000878 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000879 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000880 }
881
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000882 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000883 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000884 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000885 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000886 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000887 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000888 if (Current.is(tok::l_brace)) {
Daniel Jasper6ab54682013-07-16 18:22:10 +0000889 NewIndent =
890 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000891 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000892 AvoidBinPacking = NextNoComment &&
893 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000894 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000895 NewIndent =
896 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000897 AvoidBinPacking = !Style.BinPackParameters ||
898 (Style.ExperimentalAutoDetectBinPacking &&
899 (Current.PackingKind == PPK_OnePerLine ||
900 (!BinPackInconclusiveFunctions &&
901 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000902 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000903
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000904 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
905 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000906 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000907 }
908
Daniel Jasperacc33662013-02-08 08:22:00 +0000909 // If this '[' opens an ObjC call, determine whether all parameters fit into
910 // one line and put one per line if they don't.
911 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
912 Current.MatchingParen != NULL) {
913 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
914 State.Stack.back().BreakBeforeParameter = true;
915 }
916
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000917 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000918 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000919 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000920 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000921 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000922 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000923 --State.ParenLevel;
924 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000925 if (Current.is(tok::r_square)) {
926 // If this ends the array subscript expr, reset the corresponding value.
927 const FormatToken *NextNonComment = Current.getNextNonComment();
928 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasperfa21c072013-07-15 14:33:14 +0000929 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000930 }
Daniel Jasper400adc62013-02-08 15:28:42 +0000931
932 // Remove scopes created by fake parenthesis.
933 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000934 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000935 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000936 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000937 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000938
Daniel Jasper47a04442013-05-13 20:50:15 +0000939 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000940 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000941 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
942 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000943 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000944 }
945
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000946 State.Column += Current.CodePointCount;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000947
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000948 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000949
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000950 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
Daniel Jasper3dcd7ec2013-08-02 11:01:15 +0000951 Current.is(tok::string_literal) && Current.CanBreakBefore)
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000952 return 0;
953
Manuel Klimek1998ea22013-02-20 10:15:13 +0000954 return breakProtrudingToken(Current, State, DryRun);
955 }
956
957 /// \brief If the current token sticks out over the end of the line, break
958 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000959 ///
960 /// \returns An extra penalty if a token was broken, otherwise 0.
961 ///
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000962 /// The returned penalty will cover the cost of the additional line breaks and
963 /// column limit violation in all lines except for the last one. The penalty
964 /// for the column limit violation in the last line (and in single line
965 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000966 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000967 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000968 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000969 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000970 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000971 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000972 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000973
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000974 if (Current.is(tok::string_literal) &&
975 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000976 // Only break up default narrow strings.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000977 if (!Current.TokenText.startswith("\""))
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000978 return 0;
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000979 // Don't break string literals with escaped newlines. As clang-format must
980 // not change the string's content, it is unlikely that we'll end up with
981 // a better format.
982 if (Current.TokenText.find("\\\n") != StringRef::npos)
983 return 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000984 // Exempts unterminated string literals from line breaking. The user will
985 // likely want to terminate the string before any line breaking is done.
986 if (Current.IsUnterminatedLiteral)
Daniel Jasper59036852013-08-12 12:16:34 +0000987 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000988
Alexander Kornienkobe633902013-06-14 11:46:10 +0000989 Token.reset(new BreakableStringLiteral(Current, StartColumn,
990 Line.InPPDirective, Encoding));
Alexander Kornienko94042342013-07-16 23:47:22 +0000991 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000992 Token.reset(new BreakableBlockComment(
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000993 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000994 Line.InPPDirective, Encoding));
Daniel Jasper4a4be012013-05-06 10:24:51 +0000995 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000996 (Current.Previous == NULL ||
997 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000998 // Don't break line comments with escaped newlines. These look like
999 // separate line comments, but in fact contain a single line comment with
1000 // multiple lines including leading whitespace and the '//' markers.
1001 //
1002 // FIXME: If we want to handle them correctly, we'll need to adjust
1003 // leading whitespace in consecutive lines when changing indentation of
1004 // the first line similar to what we do with block comments.
1005 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
1006 if (EscapedNewlinePos != StringRef::npos) {
1007 State.Column =
1008 StartColumn +
1009 encoding::getCodePointCount(
1010 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
1011 1;
1012 return 0;
1013 }
1014
Alexander Kornienkobe633902013-06-14 11:46:10 +00001015 Token.reset(new BreakableLineComment(Current, StartColumn,
1016 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001017 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001018 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001019 }
Alexander Kornienkobe633902013-06-14 11:46:10 +00001020 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +00001021 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001022
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001023 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001024 bool BreakInserted = false;
1025 unsigned Penalty = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001026 unsigned RemainingTokenColumns = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +00001027 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
1028 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienkobe633902013-06-14 11:46:10 +00001029 if (!DryRun)
1030 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001031 unsigned TailOffset = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001032 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001033 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001034 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001035 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +00001036 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkoaa620e12013-07-01 13:42:42 +00001037 if (Split.first == StringRef::npos) {
1038 // The last line's penalty is handled in addNextStateToQueue().
1039 if (LineIndex < EndIndex - 1)
1040 Penalty += Style.PenaltyExcessCharacter *
1041 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001042 break;
Alexander Kornienkoaa620e12013-07-01 13:42:42 +00001043 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001044 assert(Split.first != 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001045 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001046 LineIndex, TailOffset + Split.first + Split.second,
1047 StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001048 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienkobe633902013-06-14 11:46:10 +00001049 if (!DryRun)
1050 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +00001051 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
1052 : Style.PenaltyBreakComment;
1053 unsigned ColumnsUsed =
1054 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
1055 if (ColumnsUsed > getColumnLimit()) {
1056 Penalty +=
1057 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
1058 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001059 TailOffset += Split.first + Split.second;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001060 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001061 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001062 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001063 }
1064
Alexander Kornienkoa3555e22013-06-19 19:50:11 +00001065 State.Column = RemainingTokenColumns;
1066
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001067 if (BreakInserted) {
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +00001068 // If we break the token inside a parameter list, we need to break before
1069 // the next parameter on all levels, so that the next parameter is clearly
1070 // visible. Line comments already introduce a break.
1071 if (Current.Type != TT_LineComment) {
1072 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1073 State.Stack[i].BreakBeforeParameter = true;
1074 }
1075
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001076 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001077 }
Manuel Klimek1998ea22013-02-20 10:15:13 +00001078 return Penalty;
1079 }
1080
Daniel Jasper2df93312013-01-09 10:16:05 +00001081 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001082 // In preprocessor directives reserve two chars for trailing " \"
1083 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +00001084 }
1085
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001086 /// \brief An edge in the solution space from \c Previous->State to \c State,
1087 /// inserting a newline dependent on the \c NewLine.
1088 struct StateNode {
1089 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001090 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001091 LineState State;
1092 bool NewLine;
1093 StateNode *Previous;
1094 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001095
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001096 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1097 ///
1098 /// In case of equal penalties, we want to prefer states that were inserted
1099 /// first. During state generation we make sure that we insert states first
1100 /// that break the line as late as possible.
1101 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1102
1103 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1104 /// \c State has the given \c OrderedPenalty.
1105 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1106
1107 /// \brief The BFS queue type.
1108 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1109 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001110
1111 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001113 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1114 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1115 /// find the shortest path (the one with lowest penalty) from \p InitialState
1116 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +00001117 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001118 std::set<LineState> Seen;
1119
Daniel Jasper4b866272013-02-01 11:00:45 +00001120 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001121 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001122 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1123 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1124 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001125
1126 // While not empty, take first element and follow edges.
1127 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001128 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001129 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001130 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001131 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001132 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001133 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001134 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001135
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001136 // Cut off the analysis of certain solutions if the analysis gets too
1137 // complex. See description of IgnoreStackForComparison.
1138 if (Count > 10000)
1139 Node->State.IgnoreStackForComparison = true;
1140
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001141 if (!Seen.insert(Node->State).second)
1142 // State already examined with lower penalty.
1143 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001144
Nico Weber9096fc02013-06-26 00:30:14 +00001145 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1146 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001147 }
1148
1149 if (Queue.empty())
1150 // We were unable to find a solution, do nothing.
1151 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +00001152 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001153
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001155 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +00001156 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1157 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001158 }
1159
1160 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001161 std::deque<StateNode *> Path;
1162 // We do not need a break before the initial token.
1163 while (Current->Previous) {
1164 Path.push_front(Current);
1165 Current = Current->Previous;
1166 }
1167 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1168 I != E; ++I) {
1169 DEBUG({
1170 if ((*I)->NewLine) {
1171 llvm::dbgs() << "Penalty for splitting before "
1172 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1173 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1174 }
1175 });
1176 addTokenToState((*I)->NewLine, false, State);
1177 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001178 }
1179
Manuel Klimekaf491072013-02-13 10:54:19 +00001180 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001181 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001182 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001183 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001184 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1185 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001186 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001187 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001188 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001189 return;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001190 if (NewLine) {
1191 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1192 Penalty += 15;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001193 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001194 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001195
1196 StateNode *Node = new (Allocator.Allocate())
1197 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001198 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001199 if (Node->State.Column > getColumnLimit()) {
1200 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001201 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001202 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001203
1204 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1205 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001206 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001207
Daniel Jasper4b866272013-02-01 11:00:45 +00001208 /// \brief Returns \c true, if a line break after \p State is allowed.
1209 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001210 const FormatToken &Current = *State.NextToken;
1211 const FormatToken &Previous = *Current.Previous;
1212 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001213 if (!Current.CanBreakBefore &&
1214 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001215 State.Stack.back().BreakBeforeClosingBrace))
1216 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001217 // The opening "{" of a braced list has to be on the same line as the first
1218 // element if it is nested in another braced init list or function call.
1219 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001220 Previous.Previous &&
1221 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001222 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001223 // This prevents breaks like:
1224 // ...
1225 // SomeParameter, OtherParameter).DoSomething(
1226 // ...
1227 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper0e90c3d2013-07-05 09:14:35 +00001228 if (Previous.opensScope() &&
1229 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper32a796b2013-05-27 11:50:16 +00001230 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001231 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001232 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001233
Daniel Jasper4b866272013-02-01 11:00:45 +00001234 /// \brief Returns \c true, if a line break after \p State is mandatory.
1235 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001236 const FormatToken &Current = *State.NextToken;
1237 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001238 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001239 return true;
Daniel Jasper6ab54682013-07-16 18:22:10 +00001240 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1241 State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper59036852013-08-12 12:16:34 +00001242 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001243 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001244 return true;
Daniel Jaspere33d4af2013-07-26 16:56:36 +00001245 if (Style.BreakConstructorInitializersBeforeComma) {
1246 if (Previous.Type == TT_CtorInitializerComma)
1247 return false;
1248 if (Current.Type == TT_CtorInitializerComma)
1249 return true;
1250 }
Daniel Jasperd69fc772013-05-08 14:12:04 +00001251 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
Daniel Jasperb1ae7342013-08-01 22:05:00 +00001252 (Current.Type == TT_ConditionalExpr &&
1253 !(Current.is(tok::colon) && Previous.is(tok::question)))) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001254 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001255 !Current.isTrailingComment() &&
1256 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001257 return true;
Daniel Jasperc834c702013-07-17 15:38:19 +00001258 if (Style.AlwaysBreakBeforeMultilineStrings &&
1259 State.Column > State.Stack.back().Indent &&
1260 Current.is(tok::string_literal) && Previous.isNot(tok::lessless) &&
1261 Previous.Type != TT_InlineASMColon &&
1262 ((Current.getNextNonComment() &&
1263 Current.getNextNonComment()->is(tok::string_literal)) ||
1264 (Current.TokenText.find("\\\n") != StringRef::npos)))
1265 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001266
Daniel Jaspere33d4af2013-07-26 16:56:36 +00001267 if (!Style.BreakBeforeBinaryOperators) {
1268 // If we need to break somewhere inside the LHS of a binary expression, we
1269 // should also break after the operator. Otherwise, the formatting would
1270 // hide the operator precedence, e.g. in:
1271 // if (aaaaaaaaaaaaaa ==
1272 // bbbbbbbbbbbbbb && c) {..
1273 // For comparisons, we only apply this rule, if the LHS is a binary
1274 // expression itself as otherwise, the line breaks seem superfluous.
1275 // We need special cases for ">>" which we have split into two ">" while
1276 // lexing in order to make template parsing easier.
1277 //
1278 // FIXME: We'll need something similar for styles that break before binary
1279 // operators.
1280 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1281 Previous.getPrecedence() == prec::Equality) &&
1282 Previous.Previous && Previous.Previous->Type !=
1283 TT_BinaryOperator; // For >>.
1284 bool LHSIsBinaryExpr =
1285 Previous.Previous && Previous.Previous->FakeRParens > 0;
1286 if (Previous.Type == TT_BinaryOperator &&
1287 (!IsComparison || LHSIsBinaryExpr) &&
1288 Current.Type != TT_BinaryOperator && // For >>.
1289 !Current.isTrailingComment() &&
1290 !Previous.isOneOf(tok::lessless, tok::question) &&
1291 Previous.getPrecedence() != prec::Assignment &&
1292 State.Stack.back().BreakBeforeParameter)
1293 return true;
1294 }
Daniel Jasperd69fc772013-05-08 14:12:04 +00001295
Daniel Jasper77d5d312013-07-12 15:14:05 +00001296 // Same as above, but for the first "<<" operator.
1297 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1298 State.Stack.back().FirstLessLess == 0)
1299 return true;
1300
Daniel Jasperd69fc772013-05-08 14:12:04 +00001301 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1302 // out whether it is the first parameter. Clean this up.
1303 if (Current.Type == TT_ObjCSelectorName &&
1304 Current.LongestObjCSelectorName == 0 &&
1305 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001306 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001307 if ((Current.Type == TT_CtorInitializerColon ||
1308 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001309 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001310
Daniel Jasper6331da02013-07-09 07:43:55 +00001311 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1312 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1313 State.ParenLevel == 0)
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001314 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001315 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001316 }
1317
Daniel Jasper9b334242013-03-15 14:57:30 +00001318 // Returns the total number of columns required for the remaining tokens.
1319 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001320 if (State.NextToken && State.NextToken->Previous)
1321 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001322 return 0;
1323 }
1324
Daniel Jasperf7935112012-12-03 18:12:45 +00001325 FormatStyle Style;
1326 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001327 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001328 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001329 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001330 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001331
1332 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1333 QueueType Queue;
1334 // Increasing count of \c StateNode items we have created. This is used
1335 // to create a deterministic order independent of the container.
1336 unsigned Count;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001337 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001338 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001339};
1340
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001341class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001342public:
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001343 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1344 encoding::Encoding Encoding)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001345 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Daniel Jasper8b1c6352013-08-01 17:58:23 +00001346 SourceMgr(SourceMgr), IdentTable(getFormattingLangOpts()),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001347 Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001348 Lex.SetKeepWhitespaceMode(true);
1349 }
1350
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001351 ArrayRef<FormatToken *> lex() {
1352 assert(Tokens.empty());
1353 do {
1354 Tokens.push_back(getNextToken());
1355 } while (Tokens.back()->Tok.isNot(tok::eof));
1356 return Tokens;
1357 }
1358
1359 IdentifierTable &getIdentTable() { return IdentTable; }
1360
1361private:
1362 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001363 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001364 // Create a synthesized second '>' token.
1365 Token Greater = FormatTok->Tok;
1366 FormatTok = new (Allocator.Allocate()) FormatToken;
1367 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001368 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001369 FormatTok->Tok.getLocation().getLocWithOffset(1);
1370 FormatTok->WhitespaceRange =
1371 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001372 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001373 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001374 GreaterStashed = false;
1375 return FormatTok;
1376 }
1377
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001378 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001379 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001380 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001381 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001382 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001383 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001384
1385 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001386 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001387 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001388 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001389 if (Newlines > 0)
Daniel Jasper8369aa52013-07-16 20:28:33 +00001390 FormatTok->LastNewlineOffset =
1391 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001392 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001393 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001394 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1395 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001396
Daniel Jasper8369aa52013-07-16 20:28:33 +00001397 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001398 }
Manuel Klimekef920692013-01-07 07:56:50 +00001399
Manuel Klimek1abf7892013-01-04 23:34:14 +00001400 // In case the token starts with escaped newlines, we want to
1401 // take them into account as whitespace - this pattern is quite frequent
1402 // in macro definitions.
1403 // FIXME: What do we want to do with other escaped spaces, and escaped
1404 // spaces or newlines in the middle of tokens?
1405 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001406 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1407 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001408 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001409 WhitespaceLength += 2;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001410 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001411 }
1412
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001413 TrailingWhitespace = 0;
1414 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001415 StringRef UntrimmedText = FormatTok->TokenText;
1416 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1417 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001418 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001419 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001420 FormatTok->Tok.setIdentifierInfo(&Info);
1421 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001422 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001423 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001424 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001425 GreaterStashed = true;
1426 }
1427
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001428 // Now FormatTok is the next non-whitespace token.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001429 FormatTok->CodePointCount =
1430 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001431
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001432 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001433 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001434 return FormatTok;
1435 }
1436
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001437 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001438 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001439 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001440 Lexer &Lex;
1441 SourceManager &SourceMgr;
1442 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001443 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001444 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1445 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001446
Daniel Jasper8369aa52013-07-16 20:28:33 +00001447 void readRawToken(FormatToken &Tok) {
1448 Lex.LexFromRawLexer(Tok.Tok);
1449 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1450 Tok.Tok.getLength());
1451
1452 // For formatting, treat unterminated string literals like normal string
1453 // literals.
1454 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1455 Tok.TokenText[0] == '"') {
1456 Tok.Tok.setKind(tok::string_literal);
1457 Tok.IsUnterminatedLiteral = true;
1458 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001459 }
1460};
1461
Daniel Jasperf7935112012-12-03 18:12:45 +00001462class Formatter : public UnwrappedLineConsumer {
1463public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001464 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001465 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001466 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001467 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1468 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001469 DEBUG(llvm::dbgs() << "File encoding: "
1470 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1471 : "unknown")
1472 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001473 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001474
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001475 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001476
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001477 tooling::Replacements format() {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001478 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001479
1480 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001481 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001482 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001483 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1484 Annotator.annotate(AnnotatedLines[i]);
1485 }
1486 deriveLocalStyle();
1487 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1488 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1489 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001490
1491 // Adapt level to the next line if this is a comment.
1492 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001493 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001494 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001495 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001496 !AnnotatedLines[i].First->Next)
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001497 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001498 else
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +00001499 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1500 ? &AnnotatedLines[i]
1501 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001502 }
1503
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001504 std::vector<int> IndentForLevel;
1505 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001506 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001507 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001508 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1509 E = AnnotatedLines.end();
1510 I != E; ++I) {
1511 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001512 const FormatToken *FirstTok = TheLine.First;
1513 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001514
1515 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001516 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001517 FormatPPDirective = false;
1518 if (!FormatPPDirective && TheLine.InPPDirective &&
1519 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1520 FormatPPDirective = true;
1521
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001522 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001523 while (IndentForLevel.size() <= TheLine.Level)
1524 IndentForLevel.push_back(-1);
1525 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001526 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1527 if (static_cast<int>(Indent) + Offset >= 0)
1528 Indent += Offset;
1529 tryFitMultipleLinesInOne(Indent, I, E);
1530
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001531 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001532 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001533 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001534 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001535 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001536 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001537 }
1538 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001539 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001540 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001541 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001542 // Insert a break even if there is a structural error in case where
1543 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001544 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001545 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001546 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001547 } else {
1548 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001549 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1550 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001551 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001552 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001553 TheLine.First, Whitespaces, Encoding,
1554 BinPackInconclusiveFunctions);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001555 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001556 IndentForLevel[TheLine.Level] = LevelIndent;
1557 PreviousLineWasTouched = true;
1558 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001559 // Format the first token if necessary, and notify the WhitespaceManager
1560 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001561 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1562 Tok = Tok->Next) {
1563 if (Tok == TheLine.First &&
1564 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1565 unsigned LevelIndent =
1566 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001567 // Remove trailing whitespace of the previous line if it was
1568 // touched.
1569 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1570 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1571 TheLine.InPPDirective);
1572 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001573 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001574 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001575
Manuel Klimek4fe43002013-05-22 12:51:29 +00001576 if (static_cast<int>(LevelIndent) - Offset >= 0)
1577 LevelIndent -= Offset;
1578 if (Tok->isNot(tok::comment))
1579 IndentForLevel[TheLine.Level] = LevelIndent;
1580 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001581 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001582 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001583 }
1584 // If we did not reformat this unwrapped line, the column at the end of
1585 // the last token is unchanged - thus, we can calculate the end of the
1586 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001587 PreviousLineWasTouched = false;
1588 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001589 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001590 }
1591 return Whitespaces.generateReplacements();
1592 }
1593
1594private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001595 void deriveLocalStyle() {
1596 unsigned CountBoundToVariable = 0;
1597 unsigned CountBoundToType = 0;
1598 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001599 bool HasBinPackedFunction = false;
1600 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001601 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001602 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001603 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001604 FormatToken *Tok = AnnotatedLines[i].First->Next;
1605 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001606 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001607 bool SpacesBefore =
1608 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1609 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1610 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001611 if (SpacesBefore && !SpacesAfter)
1612 ++CountBoundToVariable;
1613 else if (!SpacesBefore && SpacesAfter)
1614 ++CountBoundToType;
1615 }
1616
Daniel Jasper400adc62013-02-08 15:28:42 +00001617 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001618 Tok->Previous->Type == TT_TemplateCloser &&
1619 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001620 HasCpp03IncompatibleFormat = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001621
1622 if (Tok->PackingKind == PPK_BinPacked)
1623 HasBinPackedFunction = true;
1624 if (Tok->PackingKind == PPK_OnePerLine)
1625 HasOnePerLineFunction = true;
1626
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001627 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001628 }
1629 }
1630 if (Style.DerivePointerBinding) {
1631 if (CountBoundToType > CountBoundToVariable)
1632 Style.PointerBindsToType = true;
1633 else if (CountBoundToType < CountBoundToVariable)
1634 Style.PointerBindsToType = false;
1635 }
1636 if (Style.Standard == FormatStyle::LS_Auto) {
1637 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1638 : FormatStyle::LS_Cpp03;
1639 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001640 BinPackInconclusiveFunctions =
1641 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001642 }
1643
Manuel Klimekb95f5452013-02-08 17:38:27 +00001644 /// \brief Get the indent of \p Level from \p IndentForLevel.
1645 ///
1646 /// \p IndentForLevel must contain the indent for the level \c l
1647 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1648 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001649 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001650 if (IndentForLevel[Level] != -1)
1651 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001652 if (Level == 0)
1653 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001654 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001655 }
1656
1657 /// \brief Get the offset of the line relatively to the level.
1658 ///
1659 /// For example, 'public:' labels in classes are offset by 1 or 2
1660 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001661 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001662 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001663 return Style.AccessModifierOffset;
1664 return 0;
1665 }
1666
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001667 /// \brief Tries to merge lines into one.
1668 ///
1669 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1670 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001671 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001672 std::vector<AnnotatedLine>::iterator &I,
1673 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001674 // We can never merge stuff if there are trailing line comments.
1675 if (I->Last->Type == TT_LineComment)
1676 return;
1677
Daniel Jasperffefb3d2013-07-24 13:10:59 +00001678 if (Indent > Style.ColumnLimit)
1679 return;
1680
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001681 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001682 // If we already exceed the column limit, we set 'Limit' to 0. The different
1683 // tryMerge..() functions can then decide whether to still do merging.
1684 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001685
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001686 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001687 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001688
Daniel Jasperabca58c2013-05-15 14:09:55 +00001689 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001690 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001691 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001692 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001693 tryMergeSimpleControlStatement(I, E, Limit);
1694 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001695 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001696 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001697 } else if (I->InPPDirective &&
1698 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001699 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001700 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001701 }
1702
Daniel Jasper39825ea2013-01-14 15:40:57 +00001703 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1704 std::vector<AnnotatedLine>::iterator E,
1705 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001706 if (Limit == 0)
1707 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001708 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001709 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001710 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001711 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001712 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001713 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001714 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001715 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001716 join(Line, *(++I));
1717 }
1718
Daniel Jasper3a685df2013-05-16 12:12:21 +00001719 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1720 std::vector<AnnotatedLine>::iterator E,
1721 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001722 if (Limit == 0)
1723 return;
Manuel Klimeka027f302013-08-07 19:20:45 +00001724 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman &&
1725 (I + 1)->First->is(tok::l_brace))
1726 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001727 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001728 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001729 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001730 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001731 if (Line.Last->isNot(tok::r_paren))
1732 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001733 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001734 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001735 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1736 tok::kw_while) ||
1737 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001738 return;
1739 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001740 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1741 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001742 return;
1743 join(Line, *(++I));
1744 }
1745
1746 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001747 std::vector<AnnotatedLine>::iterator E,
1748 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001749 // No merging if the brace already is on the next line.
1750 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1751 return;
1752
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001753 // First, check that the current line allows merging. This is the case if
1754 // we're not in a control flow statement and the last token is an opening
1755 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001756 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001757 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1758 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001759 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001760 // This gets rid of all ObjC @ keywords and methods.
1761 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001762 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001763
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001764 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001765 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001766 (Tok->getNextNonComment() == NULL ||
1767 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001768 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001769 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001770 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001771 join(Line, *(I + 1));
1772 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001773 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001774 // Check that we still have three lines and they fit into the limit.
1775 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1776 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001777 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001778
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001779 // Second, check that the next line does not contain any braces - if it
1780 // does, readability declines when putting it into a single line.
1781 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1782 return;
1783 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001784 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001785 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001786 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001787 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001788
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001789 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001790 Tok = (I + 2)->First;
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001791 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001792 Tok->MustBreakBefore)
1793 return;
1794
1795 join(Line, *(I + 1));
1796 join(Line, *(I + 2));
1797 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001798 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001799 }
1800
1801 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1802 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001803 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1804 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001805 }
1806
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001807 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001808 assert(!A.Last->Next);
1809 assert(!B.First->Previous);
1810 A.Last->Next = B.First;
1811 B.First->Previous = A.Last;
1812 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1813 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1814 Tok->TotalLength += LengthA;
1815 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001816 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001817 }
1818
Daniel Jasper97b89482013-03-13 07:49:51 +00001819 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001820 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1821 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1822 Ranges[i].getBegin()) &&
1823 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1824 Range.getBegin()))
1825 return true;
1826 }
1827 return false;
1828 }
1829
1830 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001831 const FormatToken *First = TheLine.First;
1832 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001833 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001834 First->WhitespaceRange.getBegin().getLocWithOffset(
1835 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001836 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001837 return touchesRanges(LineRange);
1838 }
1839
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001840 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1841 std::vector<AnnotatedLine>::iterator E) {
1842 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001843 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001844 return false;
1845 if (touchesLine(*I))
1846 return true;
1847 }
1848 return false;
1849 }
1850
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001851 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001852 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001853 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001854 First->WhitespaceRange.getBegin(),
1855 First->WhitespaceRange.getBegin().getLocWithOffset(
1856 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001857 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001858 }
1859
1860 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001861 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001862 }
1863
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001864 /// \brief Add a new line and the required indent before the first Token
1865 /// of the \c UnwrappedLine if there was no structural parsing error.
1866 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001867 void formatFirstToken(const FormatToken &RootToken,
1868 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001869 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001870 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001871 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001872 // Remove empty lines before "}" where applicable.
1873 if (RootToken.is(tok::r_brace) &&
1874 (!RootToken.Next ||
1875 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1876 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001877 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001878 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001879
Manuel Klimek4fe43002013-05-22 12:51:29 +00001880 // Insert extra new line before access specifiers.
1881 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001882 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001883 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001884
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001885 Whitespaces.replaceWhitespace(
1886 RootToken, Newlines, Indent, Indent,
1887 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001888 }
1889
Daniel Jasperf7935112012-12-03 18:12:45 +00001890 FormatStyle Style;
1891 Lexer &Lex;
1892 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001893 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001894 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001895 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001896
1897 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001898 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001899};
1900
Craig Topperaf35e852013-06-30 22:29:28 +00001901} // end anonymous namespace
1902
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001903tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1904 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001905 std::vector<CharSourceRange> Ranges) {
1906 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001907 return formatter.format();
1908}
1909
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001910tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1911 std::vector<tooling::Range> Ranges,
1912 StringRef FileName) {
1913 FileManager Files((FileSystemOptions()));
1914 DiagnosticsEngine Diagnostics(
1915 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1916 new DiagnosticOptions);
1917 SourceManager SourceMgr(Diagnostics, Files);
1918 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1919 const clang::FileEntry *Entry =
1920 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1921 SourceMgr.overrideFileContents(Entry, Buf);
1922 FileID ID =
1923 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001924 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1925 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001926 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1927 std::vector<CharSourceRange> CharRanges;
1928 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1929 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1930 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1931 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1932 }
1933 return reformat(Style, Lex, SourceMgr, CharRanges);
1934}
1935
Alexander Kornienko1e808872013-06-28 12:51:24 +00001936LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001937 LangOptions LangOpts;
1938 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001939 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001940 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001941 LangOpts.Bool = 1;
1942 LangOpts.ObjC1 = 1;
1943 LangOpts.ObjC2 = 1;
1944 return LangOpts;
1945}
1946
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001947} // namespace format
1948} // namespace clang