blob: 125283a0c6dd6a5a6b8884fd2b40660b7539940c [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);
Alexander Kornienkod6538332013-05-07 15:32:14 +000053 }
54};
55
56template <> struct MappingTraits<clang::format::FormatStyle> {
57 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000058 if (IO.outputting()) {
59 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
60 ArrayRef<StringRef> Styles(StylesArray);
61 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
62 StringRef StyleName(Styles[i]);
Alexander Kornienko006b5c82013-05-19 00:53:30 +000063 clang::format::FormatStyle PredefinedStyle;
64 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) &&
65 Style == PredefinedStyle) {
Alexander Kornienko49149672013-05-10 11:56:10 +000066 IO.mapOptional("# BasedOnStyle", StyleName);
67 break;
68 }
69 }
70 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000071 StringRef BasedOnStyle;
72 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000073 if (!BasedOnStyle.empty())
Alexander Kornienko006b5c82013-05-19 00:53:30 +000074 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) {
75 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
76 return;
77 }
Alexander Kornienkod6538332013-05-07 15:32:14 +000078 }
79
80 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
81 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
82 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
83 Style.AllowAllParametersOfDeclarationOnNextLine);
84 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
85 Style.AllowShortIfStatementsOnASingleLine);
Daniel Jasper3a685df2013-05-16 12:12:21 +000086 IO.mapOptional("AllowShortLoopsOnASingleLine",
87 Style.AllowShortLoopsOnASingleLine);
Daniel Jasper61e6bbf2013-05-29 12:07:31 +000088 IO.mapOptional("AlwaysBreakTemplateDeclarations",
89 Style.AlwaysBreakTemplateDeclarations);
Alexander Kornienko58611712013-07-04 12:02:44 +000090 IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
91 Style.AlwaysBreakBeforeMultilineStrings);
Alexander Kornienkod6538332013-05-07 15:32:14 +000092 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
93 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
94 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
95 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
96 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
Daniel Jasperb10cbc42013-07-10 14:02:49 +000097 IO.mapOptional("ExperimentalAutoDetectBinPacking",
98 Style.ExperimentalAutoDetectBinPacking);
Alexander Kornienkod6538332013-05-07 15:32:14 +000099 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
100 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
101 IO.mapOptional("ObjCSpaceBeforeProtocolList",
102 Style.ObjCSpaceBeforeProtocolList);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000103 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
104 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000105 IO.mapOptional("PenaltyBreakFirstLessLess",
106 Style.PenaltyBreakFirstLessLess);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000107 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
108 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
109 Style.PenaltyReturnTypeOnItsOwnLine);
110 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
111 IO.mapOptional("SpacesBeforeTrailingComments",
112 Style.SpacesBeforeTrailingComments);
Daniel Jasper6ab54682013-07-16 18:22:10 +0000113 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000114 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +0000115 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000116 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000117 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Manuel Klimek836c2862013-06-21 17:25:42 +0000118 IO.mapOptional("IndentFunctionDeclarationAfterType",
119 Style.IndentFunctionDeclarationAfterType);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000120 }
121};
122}
123}
124
Daniel Jasperf7935112012-12-03 18:12:45 +0000125namespace clang {
126namespace format {
127
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000128void setDefaultPenalties(FormatStyle &Style) {
129 Style.PenaltyBreakComment = 45;
Daniel Jasperfa21c072013-07-15 14:33:14 +0000130 Style.PenaltyBreakFirstLessLess = 120;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000131 Style.PenaltyBreakString = 1000;
132 Style.PenaltyExcessCharacter = 1000000;
133}
134
Daniel Jasperf7935112012-12-03 18:12:45 +0000135FormatStyle getLLVMStyle() {
136 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000137 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000138 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000139 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000140 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000141 LLVMStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000142 LLVMStyle.AlwaysBreakTemplateDeclarations = false;
Alexander Kornienko58611712013-07-04 12:02:44 +0000143 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000144 LLVMStyle.BinPackParameters = true;
145 LLVMStyle.ColumnLimit = 80;
146 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
147 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000148 LLVMStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000149 LLVMStyle.IndentCaseLabels = false;
150 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000151 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000152 LLVMStyle.PointerBindsToType = false;
153 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper6ab54682013-07-16 18:22:10 +0000154 LLVMStyle.Cpp11BracedListStyle = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000155 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000156 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000157 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000158 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek836c2862013-06-21 17:25:42 +0000159 LLVMStyle.IndentFunctionDeclarationAfterType = false;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000160
161 setDefaultPenalties(LLVMStyle);
162 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
163
Daniel Jasperf7935112012-12-03 18:12:45 +0000164 return LLVMStyle;
165}
166
167FormatStyle getGoogleStyle() {
168 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000169 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000170 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000171 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000172 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Daniel Jasper5bd0b9e2013-05-23 18:05:18 +0000173 GoogleStyle.AllowShortLoopsOnASingleLine = true;
Daniel Jasper61e6bbf2013-05-29 12:07:31 +0000174 GoogleStyle.AlwaysBreakTemplateDeclarations = true;
Alexander Kornienko58611712013-07-04 12:02:44 +0000175 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000176 GoogleStyle.BinPackParameters = true;
177 GoogleStyle.ColumnLimit = 80;
178 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
179 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000180 GoogleStyle.ExperimentalAutoDetectBinPacking = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000181 GoogleStyle.IndentCaseLabels = true;
182 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000183 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000184 GoogleStyle.PointerBindsToType = true;
185 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper6ab54682013-07-16 18:22:10 +0000186 GoogleStyle.Cpp11BracedListStyle = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000187 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000188 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000189 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000190 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Manuel Klimek836c2862013-06-21 17:25:42 +0000191 GoogleStyle.IndentFunctionDeclarationAfterType = true;
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000192
193 setDefaultPenalties(GoogleStyle);
194 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
195
Daniel Jasperf7935112012-12-03 18:12:45 +0000196 return GoogleStyle;
197}
198
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000199FormatStyle getChromiumStyle() {
200 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000201 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000202 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper3a685df2013-05-16 12:12:21 +0000203 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000204 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000205 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
206 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000207 return ChromiumStyle;
208}
209
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000210FormatStyle getMozillaStyle() {
211 FormatStyle MozillaStyle = getLLVMStyle();
212 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
213 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
214 MozillaStyle.DerivePointerBinding = true;
215 MozillaStyle.IndentCaseLabels = true;
216 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
217 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
218 MozillaStyle.PointerBindsToType = true;
219 return MozillaStyle;
220}
221
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000222bool getPredefinedStyle(StringRef Name, FormatStyle *Style) {
Alexander Kornienkod6538332013-05-07 15:32:14 +0000223 if (Name.equals_lower("llvm"))
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000224 *Style = getLLVMStyle();
225 else if (Name.equals_lower("chromium"))
226 *Style = getChromiumStyle();
227 else if (Name.equals_lower("mozilla"))
228 *Style = getMozillaStyle();
229 else if (Name.equals_lower("google"))
230 *Style = getGoogleStyle();
231 else
232 return false;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000233
Alexander Kornienko006b5c82013-05-19 00:53:30 +0000234 return true;
Alexander Kornienkod6538332013-05-07 15:32:14 +0000235}
236
237llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
Alexander Kornienko06e00332013-05-20 15:18:01 +0000238 if (Text.trim().empty())
239 return llvm::make_error_code(llvm::errc::invalid_argument);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000240 llvm::yaml::Input Input(Text);
241 Input >> *Style;
242 return Input.error();
243}
244
245std::string configurationAsText(const FormatStyle &Style) {
246 std::string Text;
247 llvm::raw_string_ostream Stream(Text);
248 llvm::yaml::Output Output(Stream);
249 // We use the same mapping method for input and output, so we need a non-const
250 // reference here.
251 FormatStyle NonConstStyle = Style;
252 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000253 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000254}
255
Daniel Jasperacc33662013-02-08 08:22:00 +0000256// Returns the length of everything up to the first possible line break after
257// the ), ], } or > matching \c Tok.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000258static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000259 if (Tok.MatchingParen == NULL)
260 return 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000261 FormatToken *End = Tok.MatchingParen;
262 while (End->Next && !End->Next->CanBreakBefore) {
263 End = End->Next;
Daniel Jasperacc33662013-02-08 08:22:00 +0000264 }
265 return End->TotalLength - Tok.TotalLength + 1;
266}
267
Craig Topperaf35e852013-06-30 22:29:28 +0000268namespace {
269
Daniel Jasperf7935112012-12-03 18:12:45 +0000270class UnwrappedLineFormatter {
271public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000272 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000273 const AnnotatedLine &Line, unsigned FirstIndent,
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000274 const FormatToken *RootToken,
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000275 WhitespaceManager &Whitespaces,
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000276 encoding::Encoding Encoding,
277 bool BinPackInconclusiveFunctions)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000278 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000279 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000280 Whitespaces(Whitespaces), Count(0), Encoding(Encoding),
281 BinPackInconclusiveFunctions(BinPackInconclusiveFunctions) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000282
Manuel Klimek1abf7892013-01-04 23:34:14 +0000283 /// \brief Formats an \c UnwrappedLine.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000284 void format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000285 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000286 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000287 State.Column = FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000288 State.NextToken = RootToken;
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000289 State.Stack.push_back(ParenState(FirstIndent, FirstIndent,
290 /*AvoidBinPacking=*/false,
291 /*NoLineBreak=*/false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000292 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000293 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000294 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000295 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000296 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000297 State.IgnoreStackForComparison = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000298
299 // The first token has already been indented and thus consumed.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000300 moveStateToNextToken(State, /*DryRun=*/false, /*Newline=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000301
Daniel Jasper4b866272013-02-01 11:00:45 +0000302 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000303 unsigned ColumnLimit = Style.ColumnLimit;
304 if (NextLine && NextLine->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000305 !NextLine->First->HasUnescapedNewline)
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000306 ColumnLimit = getColumnLimit();
307 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000308 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000309 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000310 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000311 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000312
Daniel Jasperacc33662013-02-08 08:22:00 +0000313 // If the ObjC method declaration does not fit on a line, we should format
314 // it with one arg per line.
315 if (Line.Type == LT_ObjCMethodDecl)
316 State.Stack.back().BreakBeforeParameter = true;
317
Daniel Jasper4b866272013-02-01 11:00:45 +0000318 // Find best solution in solution space.
Manuel Klimek4fe43002013-05-22 12:51:29 +0000319 analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000320 }
321
322private:
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000323 void DebugTokenState(const FormatToken &FormatTok) {
324 const Token &Tok = FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000325 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000326 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000327 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000328 }
329
Daniel Jasper337816e2013-01-11 10:22:12 +0000330 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000331 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000332 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000333 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
334 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000335 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000336 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000337 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
338 CallContinuation(0), VariablePos(0), ContainsLineBreak(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000339
Daniel Jasperf7935112012-12-03 18:12:45 +0000340 /// \brief The position to which a specific parenthesis level needs to be
341 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000342 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000343
Daniel Jaspere9de2602012-12-06 09:56:08 +0000344 /// \brief The position of the last space on each level.
345 ///
346 /// Used e.g. to break like:
347 /// functionCall(Parameter, otherCall(
348 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000349 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000350
Daniel Jaspere9de2602012-12-06 09:56:08 +0000351 /// \brief The position the first "<<" operator encountered on each level.
352 ///
353 /// Used to align "<<" operators. 0 if no such operator has been encountered
354 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000355 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000356
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000357 /// \brief Whether a newline needs to be inserted before the block's closing
358 /// brace.
359 ///
360 /// We only want to insert a newline before the closing brace if there also
361 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 bool BreakBeforeClosingBrace;
363
Daniel Jasperca6623b2013-01-28 12:45:14 +0000364 /// \brief The column of a \c ? in a conditional expression;
365 unsigned QuestionColumn;
366
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000367 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
368 /// lines, in this context.
369 bool AvoidBinPacking;
370
371 /// \brief Break after the next comma (or all the commas in this context if
372 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000373 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000374
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000375 /// \brief Line breaking in this context would break a formatting rule.
376 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000377
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000378 /// \brief The position of the colon in an ObjC method declaration/call.
379 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000380
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000381 /// \brief The start of the most recent function in a builder-type call.
382 unsigned StartOfFunctionCall;
383
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000384 /// \brief Contains the start of array subscript expressions, so that they
385 /// can be aligned.
386 unsigned StartOfArraySubscripts;
387
Daniel Jasperc238c872013-04-02 14:33:13 +0000388 /// \brief If a nested name specifier was broken over multiple lines, this
389 /// contains the start column of the second line. Otherwise 0.
390 unsigned NestedNameSpecifierContinuation;
391
392 /// \brief If a call expression was broken over multiple lines, this
393 /// contains the start column of the second line. Otherwise 0.
394 unsigned CallContinuation;
395
Daniel Jaspera628c982013-04-03 13:36:17 +0000396 /// \brief The column of the first variable name in a variable declaration.
397 ///
398 /// Used to align further variables if necessary.
399 unsigned VariablePos;
400
Daniel Jasperee7539a2013-07-08 14:25:23 +0000401 /// \brief \c true if this \c ParenState already contains a line-break.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000402 ///
Daniel Jasperee7539a2013-07-08 14:25:23 +0000403 /// The first line break in a certain \c ParenState causes extra penalty so
404 /// that clang-format prefers similar breaks, i.e. breaks in the same
405 /// parenthesis.
406 bool ContainsLineBreak;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000407
Daniel Jasper337816e2013-01-11 10:22:12 +0000408 bool operator<(const ParenState &Other) const {
409 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000410 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000411 if (LastSpace != Other.LastSpace)
412 return LastSpace < Other.LastSpace;
413 if (FirstLessLess != Other.FirstLessLess)
414 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000415 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
416 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000417 if (QuestionColumn != Other.QuestionColumn)
418 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000419 if (AvoidBinPacking != Other.AvoidBinPacking)
420 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000421 if (BreakBeforeParameter != Other.BreakBeforeParameter)
422 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000423 if (NoLineBreak != Other.NoLineBreak)
424 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000425 if (ColonPos != Other.ColonPos)
426 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000427 if (StartOfFunctionCall != Other.StartOfFunctionCall)
428 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000429 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
430 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
Daniel Jasperc238c872013-04-02 14:33:13 +0000431 if (CallContinuation != Other.CallContinuation)
432 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000433 if (VariablePos != Other.VariablePos)
434 return VariablePos < Other.VariablePos;
Daniel Jasperee7539a2013-07-08 14:25:23 +0000435 if (ContainsLineBreak != Other.ContainsLineBreak)
436 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000437 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000438 }
439 };
440
441 /// \brief The current state when indenting a unwrapped line.
442 ///
443 /// As the indenting tries different combinations this is copied by value.
444 struct LineState {
445 /// \brief The number of used columns in the current line.
446 unsigned Column;
447
448 /// \brief The token that needs to be next formatted.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000449 const FormatToken *NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000450
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000451 /// \brief \c true if this line contains a continued for-loop section.
452 bool LineContainsContinuedForLoopSection;
453
Daniel Jasper400adc62013-02-08 15:28:42 +0000454 /// \brief The level of nesting inside (), [], <> and {}.
455 unsigned ParenLevel;
456
Daniel Jasper40c36c52013-02-18 11:05:07 +0000457 /// \brief The \c ParenLevel at the start of this line.
458 unsigned StartOfLineLevel;
459
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000460 /// \brief The lowest \c ParenLevel on the current line.
461 unsigned LowestLevelOnLine;
Daniel Jasper32a796b2013-05-27 11:50:16 +0000462
Manuel Klimek02f640a2013-02-20 15:25:48 +0000463 /// \brief The start column of the string literal, if we're in a string
464 /// literal sequence, 0 otherwise.
465 unsigned StartOfStringLiteral;
466
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 /// \brief A stack keeping track of properties applying to parenthesis
468 /// levels.
469 std::vector<ParenState> Stack;
470
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000471 /// \brief Ignore the stack of \c ParenStates for state comparison.
472 ///
473 /// In long and deeply nested unwrapped lines, the current algorithm can
474 /// be insufficient for finding the best formatting with a reasonable amount
475 /// of time and memory. Setting this flag will effectively lead to the
476 /// algorithm not analyzing some combinations. However, these combinations
477 /// rarely contain the optimal solution: In short, accepting a higher
478 /// penalty early would need to lead to different values in the \c
479 /// ParenState stack (in an otherwise identical state) and these different
480 /// values would need to lead to a significant amount of avoided penalty
481 /// later.
482 ///
483 /// FIXME: Come up with a better algorithm instead.
484 bool IgnoreStackForComparison;
485
Daniel Jasper337816e2013-01-11 10:22:12 +0000486 /// \brief Comparison operator to be able to used \c LineState in \c map.
487 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000488 if (NextToken != Other.NextToken)
489 return NextToken < Other.NextToken;
490 if (Column != Other.Column)
491 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000492 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000493 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000494 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000495 if (ParenLevel != Other.ParenLevel)
496 return ParenLevel < Other.ParenLevel;
497 if (StartOfLineLevel != Other.StartOfLineLevel)
498 return StartOfLineLevel < Other.StartOfLineLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000499 if (LowestLevelOnLine != Other.LowestLevelOnLine)
500 return LowestLevelOnLine < Other.LowestLevelOnLine;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000501 if (StartOfStringLiteral != Other.StartOfStringLiteral)
502 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperf8114cf2013-05-22 05:27:42 +0000503 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
504 return false;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000505 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 }
507 };
508
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000509 /// \brief Appends the next token to \p State and updates information
510 /// necessary for indentation.
511 ///
Nico Weberf579ab32013-06-26 02:42:46 +0000512 /// Puts the token on the current line if \p Newline is \c false and adds a
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000513 /// line break and necessary indentation otherwise.
514 ///
515 /// If \p DryRun is \c false, also creates and stores the required
516 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000517 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000518 const FormatToken &Current = *State.NextToken;
519 const FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasperf7935112012-12-03 18:12:45 +0000520
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000521 // Extra penalty that needs to be added because of the way certain line
522 // breaks are chosen.
523 unsigned ExtraPenalty = 0;
524
Daniel Jasper291f9362013-03-20 15:58:10 +0000525 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Manuel Klimek5c24cca2013-05-23 10:56:37 +0000526 // FIXME: Is this correct?
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000527 int WhitespaceLength = SourceMgr.getSpellingColumnNumber(
528 State.NextToken->WhitespaceRange.getEnd()) -
529 SourceMgr.getSpellingColumnNumber(
530 State.NextToken->WhitespaceRange.getBegin());
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000531 State.Column += WhitespaceLength + State.NextToken->CodePointCount;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000532 State.NextToken = State.NextToken->Next;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000533 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000534 }
535
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000536 // If we are continuing an expression, we want to indent an extra 4 spaces.
537 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000538 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000539 if (Newline) {
Daniel Jasperee7539a2013-07-08 14:25:23 +0000540 State.Stack.back().ContainsLineBreak = true;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000541 if (Current.is(tok::r_brace)) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000542 if (Current.BlockKind == BK_BracedInit)
543 State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
544 else
Daniel Jasper51efbad2013-07-11 21:27:40 +0000545 State.Column = FirstIndent;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000546 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000547 State.StartOfStringLiteral != 0) {
548 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000549 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000550 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000551 State.Stack.back().FirstLessLess != 0) {
552 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000553 } else if (Current.isOneOf(tok::period, tok::arrow) &&
554 Current.Type != TT_DesignatedInitializerPeriod) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000555 if (State.Stack.back().CallContinuation == 0) {
556 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000557 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000558 } else {
559 State.Column = State.Stack.back().CallContinuation;
560 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000561 } else if (Current.Type == TT_ConditionalExpr) {
562 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000563 } else if (Previous.is(tok::comma) &&
564 State.Stack.back().VariablePos != 0) {
565 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000566 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper6331da02013-07-09 07:43:55 +0000567 ((Current.Type == TT_StartOfName ||
568 Current.is(tok::kw_operator)) &&
569 State.ParenLevel == 0 &&
Manuel Klimek836c2862013-06-21 17:25:42 +0000570 (!Style.IndentFunctionDeclarationAfterType ||
571 Line.StartsDefinition))) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000572 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000573 } else if (Current.Type == TT_ObjCSelectorName) {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000574 if (State.Stack.back().ColonPos > Current.CodePointCount) {
575 State.Column = State.Stack.back().ColonPos - Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000576 } else {
577 State.Column = State.Stack.back().Indent;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000578 State.Stack.back().ColonPos = State.Column + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000579 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000580 } else if (Current.is(tok::l_square) &&
581 Current.Type != TT_ObjCMethodExpr) {
582 if (State.Stack.back().StartOfArraySubscripts != 0)
583 State.Column = State.Stack.back().StartOfArraySubscripts;
584 else
585 State.Column = ContinuationIndent;
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000586 } else if (Current.Type == TT_StartOfName ||
587 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000588 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000589 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000590 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000591 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000592 // Ensure that we fall back to indenting 4 spaces instead of just
593 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000594 if (State.Column == FirstIndent)
595 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000596 }
597
Daniel Jasper54a86022013-02-15 11:07:25 +0000598 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000599 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000600 if ((Previous.isOneOf(tok::comma, tok::semi) &&
601 !State.Stack.back().AvoidBinPacking) ||
602 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000603 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000604 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
605 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000606
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000607 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000608 unsigned NewLines = 1;
Alexander Kornienkof370ad92013-06-12 19:04:12 +0000609 if (Current.is(tok::comment))
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000610 NewLines = std::max(
611 NewLines,
612 std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek4fe43002013-05-22 12:51:29 +0000613 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
614 State.Column, Line.InPPDirective);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000615 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000616
Daniel Jasper185de242013-07-11 13:48:16 +0000617 if (!Current.isTrailingComment())
618 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000619 if (Current.isOneOf(tok::arrow, tok::period) &&
620 Current.Type != TT_DesignatedInitializerPeriod)
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000621 State.Stack.back().LastSpace += Current.CodePointCount;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000622 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000623 State.LowestLevelOnLine = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000624
625 // Any break on this level means that the parent level has been broken
626 // and we need to avoid bin packing there.
627 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
628 State.Stack[i].BreakBeforeParameter = true;
629 }
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000630 const FormatToken *TokenBefore = Current.getPreviousNonComment();
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000631 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000632 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000633 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000634 State.Stack.back().BreakBeforeParameter = true;
635
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000636 // If we break after {, we should also break before the corresponding }.
637 if (Previous.is(tok::l_brace))
638 State.Stack.back().BreakBeforeClosingBrace = true;
639
640 if (State.Stack.back().AvoidBinPacking) {
641 // If we are breaking after '(', '{', '<', this is not bin packing
642 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000643 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
644 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000645 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
646 Line.MustBeDeclaration))
647 State.Stack.back().BreakBeforeParameter = true;
648 }
Daniel Jasper4e9678f2013-07-11 20:41:21 +0000649
650 // Breaking before the first "<<" is generally not desirable.
651 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
652 ExtraPenalty += Style.PenaltyBreakFirstLessLess;
653
Daniel Jasperf7935112012-12-03 18:12:45 +0000654 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000655 if (Current.is(tok::equal) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000656 (RootToken->is(tok::kw_for) || State.ParenLevel == 0) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000657 State.Stack.back().VariablePos == 0) {
658 State.Stack.back().VariablePos = State.Column;
659 // Move over * and & if they are bound to the variable name.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000660 const FormatToken *Tok = &Previous;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000661 while (Tok && State.Stack.back().VariablePos >= Tok->CodePointCount) {
662 State.Stack.back().VariablePos -= Tok->CodePointCount;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000663 if (Tok->SpacesRequiredBefore != 0)
664 break;
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000665 Tok = Tok->Previous;
Daniel Jasper31c96b92013-04-05 09:38:50 +0000666 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000667 if (Previous.PartOfMultiVariableDeclStmt)
668 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
669 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000670
Daniel Jaspereef30492013-02-11 12:36:37 +0000671 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000672
Daniel Jasperf7935112012-12-03 18:12:45 +0000673 if (!DryRun)
Manuel Klimek4fe43002013-05-22 12:51:29 +0000674 Whitespaces.replaceWhitespace(Current, 0, Spaces,
675 State.Column + Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000676
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000677 if (Current.Type == TT_ObjCSelectorName &&
678 State.Stack.back().ColonPos == 0) {
679 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000680 State.Column + Spaces + Current.CodePointCount)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000681 State.Stack.back().ColonPos =
682 State.Stack.back().Indent + Current.LongestObjCSelectorName;
683 else
684 State.Stack.back().ColonPos =
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000685 State.Column + Spaces + Current.CodePointCount;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000686 }
687
Daniel Jasperc04baae2013-04-10 09:49:49 +0000688 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000689 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000690 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000691 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
692 State.Stack.back().AvoidBinPacking)
693 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000694
Daniel Jaspere9de2602012-12-06 09:56:08 +0000695 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000696 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000697 // Treat the condition inside an if as if it was a second function
698 // parameter, i.e. let nested calls have an indent of 4.
699 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000700 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000701 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000702 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000703 Previous.Type == TT_ConditionalExpr ||
704 Previous.Type == TT_CtorInitializerColon) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000705 !(Previous.getPrecedence() == prec::Assignment &&
Daniel Jasper7b27a102013-05-27 12:45:09 +0000706 Current.FakeLParens.empty()))
707 // Always indent relative to the RHS of the expression unless this is a
708 // simple assignment without binary expression on the RHS.
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000709 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000710 else if (Previous.Type == TT_InheritanceColon)
711 State.Stack.back().Indent = State.Column;
Daniel Jasperbd058882013-07-09 11:57:27 +0000712 else if (Previous.opensScope()) {
713 // If a function has multiple parameters (including a single parameter
Daniel Jasper6cdec7c2013-07-09 14:36:48 +0000714 // that is a binary expression) or a trailing call, indent all
Daniel Jasperbd058882013-07-09 11:57:27 +0000715 // parameters from the opening parenthesis. This avoids confusing
716 // indents like:
717 // OuterFunction(InnerFunctionCall(
718 // ParameterToInnerFunction),
719 // SecondParameterToOuterFunction);
720 bool HasMultipleParameters = !Current.FakeLParens.empty();
721 bool HasTrailingCall = false;
722 if (Previous.MatchingParen) {
723 const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
724 if (Next && Next->isOneOf(tok::period, tok::arrow))
725 HasTrailingCall = true;
726 }
727 if (HasMultipleParameters || HasTrailingCall)
728 State.Stack.back().LastSpace = State.Column;
729 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000730 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000731
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000732 return moveStateToNextToken(State, DryRun, Newline) + ExtraPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000733 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000734
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000735 /// \brief Mark the next token as consumed in \p State and modify its stacks
736 /// accordingly.
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000737 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000738 const FormatToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000739 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000740
Daniel Jaspereead02b2013-02-14 08:42:54 +0000741 if (Current.Type == TT_InheritanceColon)
742 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000743 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
744 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000745 if (Current.is(tok::l_square) &&
746 State.Stack.back().StartOfArraySubscripts == 0)
747 State.Stack.back().StartOfArraySubscripts = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000748 if (Current.is(tok::question))
749 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper0e90c3d2013-07-05 09:14:35 +0000750 if (!Current.opensScope() && !Current.closesScope())
751 State.LowestLevelOnLine =
752 std::min(State.LowestLevelOnLine, State.ParenLevel);
753 if (Current.isOneOf(tok::period, tok::arrow) &&
754 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
755 State.Stack.back().StartOfFunctionCall =
756 Current.LastInChainOfCalls ? 0
757 : State.Column + Current.CodePointCount;
Daniel Jasper37905f72013-02-21 15:00:29 +0000758 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000759 // Indent 2 from the column, so:
760 // SomeClass::SomeClass()
761 // : First(...), ...
762 // Next(...)
763 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000764 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000765 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
766 State.Stack.back().AvoidBinPacking = true;
767 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000768 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000769
Daniel Jasper6bee6822013-04-08 20:33:42 +0000770 // If return returns a binary expression, align after it.
771 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
772 State.Stack.back().LastSpace = State.Column + 7;
773
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000774 // In ObjC method declaration we align on the ":" of parameters, but we need
775 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000776 if (Current.Type == TT_ObjCMethodSpecifier)
777 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000778
Daniel Jasper400adc62013-02-08 15:28:42 +0000779 // Insert scopes created by fake parenthesis.
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000780 const FormatToken *Previous = Current.getPreviousNonComment();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000781 // Don't add extra indentation for the first fake parenthesis after
782 // 'return', assignements or opening <({[. The indentation for these cases
783 // is special cased.
784 bool SkipFirstExtraIndent =
785 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000786 (Previous && (Previous->opensScope() ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000787 Previous->getPrecedence() == prec::Assignment));
Craig Topper61ac9062013-07-08 03:55:09 +0000788 for (SmallVectorImpl<prec::Level>::const_reverse_iterator
Daniel Jasper6bee6822013-04-08 20:33:42 +0000789 I = Current.FakeLParens.rbegin(),
790 E = Current.FakeLParens.rend();
791 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000792 ParenState NewParenState = State.Stack.back();
Daniel Jasperee7539a2013-07-08 14:25:23 +0000793 NewParenState.ContainsLineBreak = false;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000794 NewParenState.Indent =
795 std::max(std::max(State.Column, NewParenState.Indent),
796 State.Stack.back().LastSpace);
797
798 // Always indent conditional expressions. Never indent expression where
799 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
800 // prec::Assignment) as those have different indentation rules. Indent
801 // other expression, unless the indentation needs to be skipped.
802 if (*I == prec::Conditional ||
803 (!SkipFirstExtraIndent && *I > prec::Assignment))
804 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000805 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000806 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000807 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000808 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000809 }
810
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000811 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000812 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000813 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000814 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000815 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000816 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000817 if (Current.is(tok::l_brace)) {
Daniel Jasper6ab54682013-07-16 18:22:10 +0000818 NewIndent =
819 LastSpace + (Style.Cpp11BracedListStyle ? 4 : Style.IndentWidth);
Alexander Kornienko1efe0a02013-07-04 14:47:51 +0000820 const FormatToken *NextNoComment = Current.getNextNonComment();
Daniel Jasperbca4bbe2013-05-28 11:30:49 +0000821 AvoidBinPacking = NextNoComment &&
822 NextNoComment->Type == TT_DesignatedInitializerPeriod;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000823 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000824 NewIndent =
825 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jasperb10cbc42013-07-10 14:02:49 +0000826 AvoidBinPacking = !Style.BinPackParameters ||
827 (Style.ExperimentalAutoDetectBinPacking &&
828 (Current.PackingKind == PPK_OnePerLine ||
829 (!BinPackInconclusiveFunctions &&
830 Current.PackingKind == PPK_Inconclusive)));
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000831 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000832
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000833 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
834 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000835 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000836 }
837
Daniel Jasperacc33662013-02-08 08:22:00 +0000838 // If this '[' opens an ObjC call, determine whether all parameters fit into
839 // one line and put one per line if they don't.
840 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
841 Current.MatchingParen != NULL) {
842 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
843 State.Stack.back().BreakBeforeParameter = true;
844 }
845
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000846 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000847 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000848 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000849 (Current.is(tok::r_brace) && State.NextToken != RootToken) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000850 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000851 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000852 --State.ParenLevel;
853 }
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000854 if (Current.is(tok::r_square)) {
855 // If this ends the array subscript expr, reset the corresponding value.
856 const FormatToken *NextNonComment = Current.getNextNonComment();
857 if (NextNonComment && NextNonComment->isNot(tok::l_square))
Daniel Jasperfa21c072013-07-15 14:33:14 +0000858 State.Stack.back().StartOfArraySubscripts = 0;
Daniel Jasperaea3bde2013-07-12 11:19:37 +0000859 }
Daniel Jasper400adc62013-02-08 15:28:42 +0000860
861 // Remove scopes created by fake parenthesis.
862 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000863 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000864 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000865 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000867
Daniel Jasper47a04442013-05-13 20:50:15 +0000868 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000869 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000870 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
871 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000872 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000873 }
874
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000875 State.Column += Current.CodePointCount;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000876
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000877 State.NextToken = State.NextToken->Next;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000878
Daniel Jasper5aad4e52013-07-12 11:37:05 +0000879 if (!Newline && Style.AlwaysBreakBeforeMultilineStrings &&
880 Current.is(tok::string_literal))
881 return 0;
882
Manuel Klimek1998ea22013-02-20 10:15:13 +0000883 return breakProtrudingToken(Current, State, DryRun);
884 }
885
886 /// \brief If the current token sticks out over the end of the line, break
887 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000888 ///
889 /// \returns An extra penalty if a token was broken, otherwise 0.
890 ///
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000891 /// The returned penalty will cover the cost of the additional line breaks and
892 /// column limit violation in all lines except for the last one. The penalty
893 /// for the column limit violation in the last line (and in single line
894 /// tokens) is handled in \c addNextStateToQueue.
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000895 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
Manuel Klimek4fe43002013-05-22 12:51:29 +0000896 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000897 llvm::OwningPtr<BreakableToken> Token;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000898 unsigned StartColumn = State.Column - Current.CodePointCount;
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000899 unsigned OriginalStartColumn =
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000900 SourceMgr.getSpellingColumnNumber(Current.getStartOfNonWhitespace()) -
Manuel Klimek591ab5a2013-05-28 13:42:28 +0000901 1;
Manuel Klimek9043c742013-05-27 15:23:34 +0000902
Daniel Jasper8bb99e82013-05-16 12:59:13 +0000903 if (Current.is(tok::string_literal) &&
904 Current.Type != TT_ImplicitStringLiteral) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000905 // Only break up default narrow strings.
Alexander Kornienkobe633902013-06-14 11:46:10 +0000906 if (!Current.TokenText.startswith("\""))
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000907 return 0;
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000908 // Don't break string literals with escaped newlines. As clang-format must
909 // not change the string's content, it is unlikely that we'll end up with
910 // a better format.
911 if (Current.TokenText.find("\\\n") != StringRef::npos)
912 return 0;
Daniel Jasper8369aa52013-07-16 20:28:33 +0000913 // Exempts unterminated string literals from line breaking. The user will
914 // likely want to terminate the string before any line breaking is done.
915 if (Current.IsUnterminatedLiteral)
916 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000917
Alexander Kornienkobe633902013-06-14 11:46:10 +0000918 Token.reset(new BreakableStringLiteral(Current, StartColumn,
919 Line.InPPDirective, Encoding));
Alexander Kornienko94042342013-07-16 23:47:22 +0000920 } else if (Current.Type == TT_BlockComment && Current.isTrailingComment()) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000921 Token.reset(new BreakableBlockComment(
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000922 Style, Current, StartColumn, OriginalStartColumn, !Current.Previous,
Alexander Kornienkobe633902013-06-14 11:46:10 +0000923 Line.InPPDirective, Encoding));
Daniel Jasper4a4be012013-05-06 10:24:51 +0000924 } else if (Current.Type == TT_LineComment &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +0000925 (Current.Previous == NULL ||
926 Current.Previous->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko657c67b2013-07-16 21:06:13 +0000927 // Don't break line comments with escaped newlines. These look like
928 // separate line comments, but in fact contain a single line comment with
929 // multiple lines including leading whitespace and the '//' markers.
930 //
931 // FIXME: If we want to handle them correctly, we'll need to adjust
932 // leading whitespace in consecutive lines when changing indentation of
933 // the first line similar to what we do with block comments.
934 StringRef::size_type EscapedNewlinePos = Current.TokenText.find("\\\n");
935 if (EscapedNewlinePos != StringRef::npos) {
936 State.Column =
937 StartColumn +
938 encoding::getCodePointCount(
939 Current.TokenText.substr(0, EscapedNewlinePos), Encoding) +
940 1;
941 return 0;
942 }
943
Alexander Kornienkobe633902013-06-14 11:46:10 +0000944 Token.reset(new BreakableLineComment(Current, StartColumn,
945 Line.InPPDirective, Encoding));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000946 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +0000947 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000948 }
Alexander Kornienkobe633902013-06-14 11:46:10 +0000949 if (Current.UnbreakableTailLength >= getColumnLimit())
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000950 return 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000951
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000952 unsigned RemainingSpace = getColumnLimit() - Current.UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000953 bool BreakInserted = false;
954 unsigned Penalty = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000955 unsigned RemainingTokenColumns = 0;
Manuel Klimek9043c742013-05-27 15:23:34 +0000956 for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
957 LineIndex != EndIndex; ++LineIndex) {
Alexander Kornienkobe633902013-06-14 11:46:10 +0000958 if (!DryRun)
959 Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000960 unsigned TailOffset = 0;
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000961 RemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000962 LineIndex, TailOffset, StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000963 while (RemainingTokenColumns > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000964 BreakableToken::Split Split =
Manuel Klimek4fe43002013-05-22 12:51:29 +0000965 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000966 if (Split.first == StringRef::npos) {
967 // The last line's penalty is handled in addNextStateToQueue().
968 if (LineIndex < EndIndex - 1)
969 Penalty += Style.PenaltyExcessCharacter *
970 (RemainingTokenColumns - RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000971 break;
Alexander Kornienkoaa620e12013-07-01 13:42:42 +0000972 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000973 assert(Split.first != 0);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000974 unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000975 LineIndex, TailOffset + Split.first + Split.second,
976 StringRef::npos);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000977 assert(NewRemainingTokenColumns < RemainingTokenColumns);
Alexander Kornienkobe633902013-06-14 11:46:10 +0000978 if (!DryRun)
979 Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
Alexander Kornienkodd7ece52013-06-07 16:02:52 +0000980 Penalty += Current.is(tok::string_literal) ? Style.PenaltyBreakString
981 : Style.PenaltyBreakComment;
982 unsigned ColumnsUsed =
983 Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
984 if (ColumnsUsed > getColumnLimit()) {
985 Penalty +=
986 Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit());
987 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000988 TailOffset += Split.first + Split.second;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +0000989 RemainingTokenColumns = NewRemainingTokenColumns;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000990 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000991 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000992 }
993
Alexander Kornienkoa3555e22013-06-19 19:50:11 +0000994 State.Column = RemainingTokenColumns;
995
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000996 if (BreakInserted) {
Alexander Kornienko4d26b6e2013-06-17 12:59:44 +0000997 // If we break the token inside a parameter list, we need to break before
998 // the next parameter on all levels, so that the next parameter is clearly
999 // visible. Line comments already introduce a break.
1000 if (Current.Type != TT_LineComment) {
1001 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1002 State.Stack[i].BreakBeforeParameter = true;
1003 }
1004
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001005 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001006 }
Manuel Klimek1998ea22013-02-20 10:15:13 +00001007 return Penalty;
1008 }
1009
Daniel Jasper2df93312013-01-09 10:16:05 +00001010 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001011 // In preprocessor directives reserve two chars for trailing " \"
1012 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +00001013 }
1014
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001015 /// \brief An edge in the solution space from \c Previous->State to \c State,
1016 /// inserting a newline dependent on the \c NewLine.
1017 struct StateNode {
1018 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001019 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001020 LineState State;
1021 bool NewLine;
1022 StateNode *Previous;
1023 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001024
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001025 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1026 ///
1027 /// In case of equal penalties, we want to prefer states that were inserted
1028 /// first. During state generation we make sure that we insert states first
1029 /// that break the line as late as possible.
1030 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1031
1032 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1033 /// \c State has the given \c OrderedPenalty.
1034 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1035
1036 /// \brief The BFS queue type.
1037 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1038 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001039
1040 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001042 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1043 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1044 /// find the shortest path (the one with lowest penalty) from \p InitialState
1045 /// to a state where all tokens are placed.
Manuel Klimek4fe43002013-05-22 12:51:29 +00001046 void analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001047 std::set<LineState> Seen;
1048
Daniel Jasper4b866272013-02-01 11:00:45 +00001049 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001050 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001051 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1052 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1053 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001054
1055 // While not empty, take first element and follow edges.
1056 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001057 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001058 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001059 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +00001060 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001061 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001062 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001063 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001064
Daniel Jasperf8114cf2013-05-22 05:27:42 +00001065 // Cut off the analysis of certain solutions if the analysis gets too
1066 // complex. See description of IgnoreStackForComparison.
1067 if (Count > 10000)
1068 Node->State.IgnoreStackForComparison = true;
1069
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001070 if (!Seen.insert(Node->State).second)
1071 // State already examined with lower penalty.
1072 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001073
Nico Weber9096fc02013-06-26 00:30:14 +00001074 addNextStateToQueue(Penalty, Node, /*NewLine=*/false);
1075 addNextStateToQueue(Penalty, Node, /*NewLine=*/true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001076 }
1077
1078 if (Queue.empty())
1079 // We were unable to find a solution, do nothing.
1080 // FIXME: Add diagnostic?
Manuel Klimek4fe43002013-05-22 12:51:29 +00001081 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001082
Daniel Jasper4b866272013-02-01 11:00:45 +00001083 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001084 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +00001085 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
1086 DEBUG(llvm::dbgs() << "---\n");
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001087 }
1088
1089 void reconstructPath(LineState &State, StateNode *Current) {
Manuel Klimek4c5c28b2013-05-29 15:10:11 +00001090 std::deque<StateNode *> Path;
1091 // We do not need a break before the initial token.
1092 while (Current->Previous) {
1093 Path.push_front(Current);
1094 Current = Current->Previous;
1095 }
1096 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
1097 I != E; ++I) {
1098 DEBUG({
1099 if ((*I)->NewLine) {
1100 llvm::dbgs() << "Penalty for splitting before "
1101 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
1102 << (*I)->Previous->State.NextToken->SplitPenalty << "\n";
1103 }
1104 });
1105 addTokenToState((*I)->NewLine, false, State);
1106 }
Daniel Jasper4b866272013-02-01 11:00:45 +00001107 }
1108
Manuel Klimekaf491072013-02-13 10:54:19 +00001109 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001110 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001111 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001112 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001113 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1114 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001115 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001116 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001117 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001118 return;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001119 if (NewLine) {
1120 if (!PreviousNode->State.Stack.back().ContainsLineBreak)
1121 Penalty += 15;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001122 Penalty += PreviousNode->State.NextToken->SplitPenalty;
Daniel Jasperee7539a2013-07-08 14:25:23 +00001123 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001124
1125 StateNode *Node = new (Allocator.Allocate())
1126 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001127 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001128 if (Node->State.Column > getColumnLimit()) {
1129 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001130 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001131 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001132
1133 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1134 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001135 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001136
Daniel Jasper4b866272013-02-01 11:00:45 +00001137 /// \brief Returns \c true, if a line break after \p State is allowed.
1138 bool canBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001139 const FormatToken &Current = *State.NextToken;
1140 const FormatToken &Previous = *Current.Previous;
1141 assert(&Previous == Current.Previous);
Daniel Jasper473c62c2013-05-17 09:35:01 +00001142 if (!Current.CanBreakBefore &&
1143 !(Current.is(tok::r_brace) &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001144 State.Stack.back().BreakBeforeClosingBrace))
1145 return false;
Daniel Jasper473c62c2013-05-17 09:35:01 +00001146 // The opening "{" of a braced list has to be on the same line as the first
1147 // element if it is nested in another braced init list or function call.
1148 if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001149 Previous.Previous &&
1150 Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
Daniel Jasper473c62c2013-05-17 09:35:01 +00001151 return false;
Daniel Jasper32a796b2013-05-27 11:50:16 +00001152 // This prevents breaks like:
1153 // ...
1154 // SomeParameter, OtherParameter).DoSomething(
1155 // ...
1156 // As they hide "DoSomething" and are generally bad for readability.
Daniel Jasper0e90c3d2013-07-05 09:14:35 +00001157 if (Previous.opensScope() &&
1158 State.LowestLevelOnLine < State.StartOfLineLevel)
Daniel Jasper32a796b2013-05-27 11:50:16 +00001159 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +00001160 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +00001161 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001162
Daniel Jasper4b866272013-02-01 11:00:45 +00001163 /// \brief Returns \c true, if a line break after \p State is mandatory.
1164 bool mustBreak(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001165 const FormatToken &Current = *State.NextToken;
1166 const FormatToken &Previous = *Current.Previous;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001167 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +00001168 return true;
Daniel Jasper6ab54682013-07-16 18:22:10 +00001169 if (!Style.Cpp11BracedListStyle && Current.is(tok::r_brace) &&
1170 State.Stack.back().BreakBeforeClosingBrace)
1171 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001172 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +00001173 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001174 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
1175 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001176 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001177 !Current.isTrailingComment() &&
1178 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001179 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001180
1181 // If we need to break somewhere inside the LHS of a binary expression, we
Daniel Jasper7ae41cd2013-07-03 10:34:47 +00001182 // should also break after the operator. Otherwise, the formatting would
1183 // hide the operator precedence, e.g. in:
1184 // if (aaaaaaaaaaaaaa ==
1185 // bbbbbbbbbbbbbb && c) {..
1186 // For comparisons, we only apply this rule, if the LHS is a binary
1187 // expression itself as otherwise, the line breaks seem superfluous.
1188 // We need special cases for ">>" which we have split into two ">" while
1189 // lexing in order to make template parsing easier.
1190 bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
1191 Previous.getPrecedence() == prec::Equality) &&
1192 Previous.Previous &&
1193 Previous.Previous->Type != TT_BinaryOperator; // For >>.
1194 bool LHSIsBinaryExpr =
1195 Previous.Previous && Previous.Previous->FakeRParens > 0;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001196 if (Previous.Type == TT_BinaryOperator &&
Daniel Jasper7ae41cd2013-07-03 10:34:47 +00001197 (!IsComparison || LHSIsBinaryExpr) &&
1198 Current.Type != TT_BinaryOperator && // For >>.
Daniel Jasper68d888c2013-06-03 08:42:05 +00001199 !Current.isTrailingComment() &&
Daniel Jasperd69fc772013-05-08 14:12:04 +00001200 !Previous.isOneOf(tok::lessless, tok::question) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001201 Previous.getPrecedence() != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001202 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001203 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001204
Daniel Jasper77d5d312013-07-12 15:14:05 +00001205 // Same as above, but for the first "<<" operator.
1206 if (Current.is(tok::lessless) && State.Stack.back().BreakBeforeParameter &&
1207 State.Stack.back().FirstLessLess == 0)
1208 return true;
1209
Daniel Jasperd69fc772013-05-08 14:12:04 +00001210 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1211 // out whether it is the first parameter. Clean this up.
1212 if (Current.Type == TT_ObjCSelectorName &&
1213 Current.LongestObjCSelectorName == 0 &&
1214 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001215 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001216 if ((Current.Type == TT_CtorInitializerColon ||
1217 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001218 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001219
Daniel Jasper6331da02013-07-09 07:43:55 +00001220 if ((Current.Type == TT_StartOfName || Current.is(tok::kw_operator)) &&
1221 Line.MightBeFunctionDecl && State.Stack.back().BreakBeforeParameter &&
1222 State.ParenLevel == 0)
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001223 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001224 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001225 }
1226
Daniel Jasper9b334242013-03-15 14:57:30 +00001227 // Returns the total number of columns required for the remaining tokens.
1228 unsigned getRemainingLength(const LineState &State) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001229 if (State.NextToken && State.NextToken->Previous)
1230 return Line.Last->TotalLength - State.NextToken->Previous->TotalLength;
Daniel Jasper9b334242013-03-15 14:57:30 +00001231 return 0;
1232 }
1233
Daniel Jasperf7935112012-12-03 18:12:45 +00001234 FormatStyle Style;
1235 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001236 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001237 const unsigned FirstIndent;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001238 const FormatToken *RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001239 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001240
1241 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1242 QueueType Queue;
1243 // Increasing count of \c StateNode items we have created. This is used
1244 // to create a deterministic order independent of the container.
1245 unsigned Count;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001246 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001247 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001248};
1249
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001250class FormatTokenLexer {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001251public:
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001252 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr,
1253 encoding::Encoding Encoding)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001254 : FormatTok(NULL), GreaterStashed(false), TrailingWhitespace(0), Lex(Lex),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001255 SourceMgr(SourceMgr), IdentTable(Lex.getLangOpts()),
1256 Encoding(Encoding) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001257 Lex.SetKeepWhitespaceMode(true);
1258 }
1259
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001260 ArrayRef<FormatToken *> lex() {
1261 assert(Tokens.empty());
1262 do {
1263 Tokens.push_back(getNextToken());
1264 } while (Tokens.back()->Tok.isNot(tok::eof));
1265 return Tokens;
1266 }
1267
1268 IdentifierTable &getIdentTable() { return IdentTable; }
1269
1270private:
1271 FormatToken *getNextToken() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001272 if (GreaterStashed) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001273 // Create a synthesized second '>' token.
1274 Token Greater = FormatTok->Tok;
1275 FormatTok = new (Allocator.Allocate()) FormatToken;
1276 FormatTok->Tok = Greater;
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001277 SourceLocation GreaterLocation =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001278 FormatTok->Tok.getLocation().getLocWithOffset(1);
1279 FormatTok->WhitespaceRange =
1280 SourceRange(GreaterLocation, GreaterLocation);
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001281 FormatTok->TokenText = ">";
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001282 FormatTok->CodePointCount = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001283 GreaterStashed = false;
1284 return FormatTok;
1285 }
1286
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001287 FormatTok = new (Allocator.Allocate()) FormatToken;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001288 readRawToken(*FormatTok);
Manuel Klimek9043c742013-05-27 15:23:34 +00001289 SourceLocation WhitespaceStart =
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001290 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001291 if (SourceMgr.getFileOffset(WhitespaceStart) == 0)
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001292 FormatTok->IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001293
1294 // Consume and record whitespace until we find a significant token.
Manuel Klimek9043c742013-05-27 15:23:34 +00001295 unsigned WhitespaceLength = TrailingWhitespace;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001296 while (FormatTok->Tok.is(tok::unknown)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001297 unsigned Newlines = FormatTok->TokenText.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001298 if (Newlines > 0)
Daniel Jasper8369aa52013-07-16 20:28:33 +00001299 FormatTok->LastNewlineOffset =
1300 WhitespaceLength + FormatTok->TokenText.rfind('\n') + 1;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001301 FormatTok->NewlinesBefore += Newlines;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001302 unsigned EscapedNewlines = FormatTok->TokenText.count("\\\n");
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001303 FormatTok->HasUnescapedNewline |= EscapedNewlines != Newlines;
1304 WhitespaceLength += FormatTok->Tok.getLength();
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001305
Daniel Jasper8369aa52013-07-16 20:28:33 +00001306 readRawToken(*FormatTok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001307 }
Manuel Klimekef920692013-01-07 07:56:50 +00001308
Manuel Klimek1abf7892013-01-04 23:34:14 +00001309 // In case the token starts with escaped newlines, we want to
1310 // take them into account as whitespace - this pattern is quite frequent
1311 // in macro definitions.
1312 // FIXME: What do we want to do with other escaped spaces, and escaped
1313 // spaces or newlines in the middle of tokens?
1314 // FIXME: Add a more explicit test.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001315 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
1316 FormatTok->TokenText[1] == '\n') {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001317 // FIXME: ++FormatTok->NewlinesBefore is missing...
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001318 WhitespaceLength += 2;
Daniel Jasper8369aa52013-07-16 20:28:33 +00001319 FormatTok->TokenText = FormatTok->TokenText.substr(2);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001320 }
1321
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001322 TrailingWhitespace = 0;
1323 if (FormatTok->Tok.is(tok::comment)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001324 StringRef UntrimmedText = FormatTok->TokenText;
1325 FormatTok->TokenText = FormatTok->TokenText.rtrim();
1326 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001327 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
Daniel Jasper8369aa52013-07-16 20:28:33 +00001328 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001329 FormatTok->Tok.setIdentifierInfo(&Info);
1330 FormatTok->Tok.setKind(Info.getTokenID());
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001331 } else if (FormatTok->Tok.is(tok::greatergreater)) {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001332 FormatTok->Tok.setKind(tok::greater);
Daniel Jasper8369aa52013-07-16 20:28:33 +00001333 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001334 GreaterStashed = true;
1335 }
1336
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001337 // Now FormatTok is the next non-whitespace token.
Daniel Jasper8369aa52013-07-16 20:28:33 +00001338 FormatTok->CodePointCount =
1339 encoding::getCodePointCount(FormatTok->TokenText, Encoding);
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001340
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001341 FormatTok->WhitespaceRange = SourceRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001342 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001343 return FormatTok;
1344 }
1345
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001346 FormatToken *FormatTok;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001347 bool GreaterStashed;
Manuel Klimek9043c742013-05-27 15:23:34 +00001348 unsigned TrailingWhitespace;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349 Lexer &Lex;
1350 SourceManager &SourceMgr;
1351 IdentifierTable IdentTable;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001352 encoding::Encoding Encoding;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001353 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
1354 SmallVector<FormatToken *, 16> Tokens;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001355
Daniel Jasper8369aa52013-07-16 20:28:33 +00001356 void readRawToken(FormatToken &Tok) {
1357 Lex.LexFromRawLexer(Tok.Tok);
1358 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1359 Tok.Tok.getLength());
1360
1361 // For formatting, treat unterminated string literals like normal string
1362 // literals.
1363 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() &&
1364 Tok.TokenText[0] == '"') {
1365 Tok.Tok.setKind(tok::string_literal);
1366 Tok.IsUnterminatedLiteral = true;
1367 }
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001368 }
1369};
1370
Daniel Jasperf7935112012-12-03 18:12:45 +00001371class Formatter : public UnwrappedLineConsumer {
1372public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001373 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001374 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001375 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001376 Whitespaces(SourceMgr, Style), Ranges(Ranges),
1377 Encoding(encoding::detectEncoding(Lex.getBuffer())) {
Daniel Jasperfa21c072013-07-15 14:33:14 +00001378 DEBUG(llvm::dbgs() << "File encoding: "
1379 << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
1380 : "unknown")
1381 << "\n");
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001382 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001383
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001384 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001385
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001386 tooling::Replacements format() {
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001387 FormatTokenLexer Tokens(Lex, SourceMgr, Encoding);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001388
1389 UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001390 bool StructuralError = Parser.parse();
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001391 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001392 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1393 Annotator.annotate(AnnotatedLines[i]);
1394 }
1395 deriveLocalStyle();
1396 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1397 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1398 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001399
1400 // Adapt level to the next line if this is a comment.
1401 // FIXME: Can/should this be done in the UnwrappedLineParser?
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001402 const AnnotatedLine *NextNonCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001403 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001404 if (NextNonCommentLine && AnnotatedLines[i].First->is(tok::comment) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001405 !AnnotatedLines[i].First->Next)
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001406 AnnotatedLines[i].Level = NextNonCommentLine->Level;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001407 else
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +00001408 NextNonCommentLine = AnnotatedLines[i].First->isNot(tok::r_brace)
1409 ? &AnnotatedLines[i]
1410 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001411 }
1412
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001413 std::vector<int> IndentForLevel;
1414 bool PreviousLineWasTouched = false;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001415 const FormatToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001416 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001417 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1418 E = AnnotatedLines.end();
1419 I != E; ++I) {
1420 const AnnotatedLine &TheLine = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001421 const FormatToken *FirstTok = TheLine.First;
1422 int Offset = getIndentOffset(*TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001423
1424 // Check whether this line is part of a formatted preprocessor directive.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001425 if (FirstTok->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001426 FormatPPDirective = false;
1427 if (!FormatPPDirective && TheLine.InPPDirective &&
1428 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1429 FormatPPDirective = true;
1430
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001431 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001432 while (IndentForLevel.size() <= TheLine.Level)
1433 IndentForLevel.push_back(-1);
1434 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001435 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1436 if (static_cast<int>(Indent) + Offset >= 0)
1437 Indent += Offset;
1438 tryFitMultipleLinesInOne(Indent, I, E);
1439
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001440 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001441 if (TheLine.First->is(tok::eof)) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001442 if (PreviousLineWasTouched) {
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001443 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001444 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001445 /*TargetColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001446 }
1447 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001448 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001449 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001450 if (FirstTok->WhitespaceRange.isValid() &&
Manuel Klimek1a18c402013-04-12 14:13:36 +00001451 // Insert a break even if there is a structural error in case where
1452 // we break apart a line consisting of multiple unwrapped lines.
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001453 (FirstTok->NewlinesBefore == 0 || !StructuralError)) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001454 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001455 TheLine.InPPDirective);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001456 } else {
1457 Indent = LevelIndent =
Manuel Klimek591ab5a2013-05-28 13:42:28 +00001458 SourceMgr.getSpellingColumnNumber(FirstTok->Tok.getLocation()) -
1459 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001460 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001461 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001462 TheLine.First, Whitespaces, Encoding,
1463 BinPackInconclusiveFunctions);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001464 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001465 IndentForLevel[TheLine.Level] = LevelIndent;
1466 PreviousLineWasTouched = true;
1467 } else {
Manuel Klimek4fe43002013-05-22 12:51:29 +00001468 // Format the first token if necessary, and notify the WhitespaceManager
1469 // about the unchanged whitespace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001470 for (const FormatToken *Tok = TheLine.First; Tok != NULL;
1471 Tok = Tok->Next) {
1472 if (Tok == TheLine.First &&
1473 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
1474 unsigned LevelIndent =
1475 SourceMgr.getSpellingColumnNumber(Tok->Tok.getLocation()) - 1;
Manuel Klimek4fe43002013-05-22 12:51:29 +00001476 // Remove trailing whitespace of the previous line if it was
1477 // touched.
1478 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) {
1479 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent,
1480 TheLine.InPPDirective);
1481 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001482 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001483 }
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001484
Manuel Klimek4fe43002013-05-22 12:51:29 +00001485 if (static_cast<int>(LevelIndent) - Offset >= 0)
1486 LevelIndent -= Offset;
1487 if (Tok->isNot(tok::comment))
1488 IndentForLevel[TheLine.Level] = LevelIndent;
1489 } else {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001490 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective);
Manuel Klimek4fe43002013-05-22 12:51:29 +00001491 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001492 }
1493 // If we did not reformat this unwrapped line, the column at the end of
1494 // the last token is unchanged - thus, we can calculate the end of the
1495 // last token.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001496 PreviousLineWasTouched = false;
1497 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001498 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001499 }
1500 return Whitespaces.generateReplacements();
1501 }
1502
1503private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001504 void deriveLocalStyle() {
1505 unsigned CountBoundToVariable = 0;
1506 unsigned CountBoundToType = 0;
1507 bool HasCpp03IncompatibleFormat = false;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001508 bool HasBinPackedFunction = false;
1509 bool HasOnePerLineFunction = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001510 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001511 if (!AnnotatedLines[i].First->Next)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001512 continue;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001513 FormatToken *Tok = AnnotatedLines[i].First->Next;
1514 while (Tok->Next) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001515 if (Tok->Type == TT_PointerOrReference) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001516 bool SpacesBefore =
1517 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
1518 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
1519 Tok->Next->WhitespaceRange.getEnd();
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001520 if (SpacesBefore && !SpacesAfter)
1521 ++CountBoundToVariable;
1522 else if (!SpacesBefore && SpacesAfter)
1523 ++CountBoundToType;
1524 }
1525
Daniel Jasper400adc62013-02-08 15:28:42 +00001526 if (Tok->Type == TT_TemplateCloser &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001527 Tok->Previous->Type == TT_TemplateCloser &&
1528 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd())
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001529 HasCpp03IncompatibleFormat = true;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001530
1531 if (Tok->PackingKind == PPK_BinPacked)
1532 HasBinPackedFunction = true;
1533 if (Tok->PackingKind == PPK_OnePerLine)
1534 HasOnePerLineFunction = true;
1535
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001536 Tok = Tok->Next;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001537 }
1538 }
1539 if (Style.DerivePointerBinding) {
1540 if (CountBoundToType > CountBoundToVariable)
1541 Style.PointerBindsToType = true;
1542 else if (CountBoundToType < CountBoundToVariable)
1543 Style.PointerBindsToType = false;
1544 }
1545 if (Style.Standard == FormatStyle::LS_Auto) {
1546 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1547 : FormatStyle::LS_Cpp03;
1548 }
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001549 BinPackInconclusiveFunctions =
1550 HasBinPackedFunction || !HasOnePerLineFunction;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001551 }
1552
Manuel Klimekb95f5452013-02-08 17:38:27 +00001553 /// \brief Get the indent of \p Level from \p IndentForLevel.
1554 ///
1555 /// \p IndentForLevel must contain the indent for the level \c l
1556 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1557 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001558 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001559 if (IndentForLevel[Level] != -1)
1560 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001561 if (Level == 0)
1562 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001563 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001564 }
1565
1566 /// \brief Get the offset of the line relatively to the level.
1567 ///
1568 /// For example, 'public:' labels in classes are offset by 1 or 2
1569 /// characters to the left from their level.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001570 int getIndentOffset(const FormatToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001571 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001572 return Style.AccessModifierOffset;
1573 return 0;
1574 }
1575
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001576 /// \brief Tries to merge lines into one.
1577 ///
1578 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1579 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001580 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001581 std::vector<AnnotatedLine>::iterator &I,
1582 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001583 // We can never merge stuff if there are trailing line comments.
1584 if (I->Last->Type == TT_LineComment)
1585 return;
1586
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001587 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001588 // If we already exceed the column limit, we set 'Limit' to 0. The different
1589 // tryMerge..() functions can then decide whether to still do merging.
1590 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001591
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001592 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001593 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001594
Daniel Jasperabca58c2013-05-15 14:09:55 +00001595 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001596 tryMergeSimpleBlock(I, E, Limit);
Daniel Jasper3a685df2013-05-16 12:12:21 +00001597 } else if (Style.AllowShortIfStatementsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001598 I->First->is(tok::kw_if)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001599 tryMergeSimpleControlStatement(I, E, Limit);
1600 } else if (Style.AllowShortLoopsOnASingleLine &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001601 I->First->isOneOf(tok::kw_for, tok::kw_while)) {
Daniel Jasper3a685df2013-05-16 12:12:21 +00001602 tryMergeSimpleControlStatement(I, E, Limit);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001603 } else if (I->InPPDirective &&
1604 (I->First->HasUnescapedNewline || I->First->IsFirst)) {
Daniel Jasper39825ea2013-01-14 15:40:57 +00001605 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001606 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001607 }
1608
Daniel Jasper39825ea2013-01-14 15:40:57 +00001609 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1610 std::vector<AnnotatedLine>::iterator E,
1611 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001612 if (Limit == 0)
1613 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001614 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001615 if (!(I + 1)->InPPDirective || (I + 1)->First->HasUnescapedNewline)
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001616 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001617 if (I + 2 != E && (I + 2)->InPPDirective &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001618 !(I + 2)->First->HasUnescapedNewline)
Daniel Jasper39825ea2013-01-14 15:40:57 +00001619 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001620 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001621 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001622 join(Line, *(++I));
1623 }
1624
Daniel Jasper3a685df2013-05-16 12:12:21 +00001625 void tryMergeSimpleControlStatement(std::vector<AnnotatedLine>::iterator &I,
1626 std::vector<AnnotatedLine>::iterator E,
1627 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001628 if (Limit == 0)
1629 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001630 if ((I + 1)->InPPDirective != I->InPPDirective ||
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001631 ((I + 1)->InPPDirective && (I + 1)->First->HasUnescapedNewline))
Manuel Klimekda087612013-01-18 14:46:43 +00001632 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001633 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001634 if (Line.Last->isNot(tok::r_paren))
1635 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001636 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001637 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001638 if ((I + 1)->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
1639 tok::kw_while) ||
1640 (I + 1)->First->Type == TT_LineComment)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001641 return;
1642 // Only inline simple if's (no nested if or else).
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001643 if (I + 2 != E && Line.First->is(tok::kw_if) &&
1644 (I + 2)->First->is(tok::kw_else))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001645 return;
1646 join(Line, *(++I));
1647 }
1648
1649 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001650 std::vector<AnnotatedLine>::iterator E,
1651 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001652 // No merging if the brace already is on the next line.
1653 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1654 return;
1655
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001656 // First, check that the current line allows merging. This is the case if
1657 // we're not in a control flow statement and the last token is an opening
1658 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001659 AnnotatedLine &Line = *I;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001660 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1661 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001662 tok::kw_for,
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001663 // This gets rid of all ObjC @ keywords and methods.
1664 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001665 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001666
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001667 FormatToken *Tok = (I + 1)->First;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001668 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001669 (Tok->getNextNonComment() == NULL ||
1670 Tok->getNextNonComment()->is(tok::semi))) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001671 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001672 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001673 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001674 join(Line, *(I + 1));
1675 I += 1;
Daniel Jaspera9eb2aa2013-05-31 14:56:20 +00001676 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001677 // Check that we still have three lines and they fit into the limit.
1678 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1679 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001680 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001681
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001682 // Second, check that the next line does not contain any braces - if it
1683 // does, readability declines when putting it into a single line.
1684 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1685 return;
1686 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001687 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001688 return;
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001689 Tok = Tok->Next;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001690 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001691
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001692 // Last, check that the third line contains a single closing brace.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001693 Tok = (I + 2)->First;
Alexander Kornienko1efe0a02013-07-04 14:47:51 +00001694 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001695 Tok->MustBreakBefore)
1696 return;
1697
1698 join(Line, *(I + 1));
1699 join(Line, *(I + 2));
1700 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001701 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001702 }
1703
1704 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1705 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001706 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1707 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001708 }
1709
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001710 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001711 assert(!A.Last->Next);
1712 assert(!B.First->Previous);
1713 A.Last->Next = B.First;
1714 B.First->Previous = A.Last;
1715 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
1716 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
1717 Tok->TotalLength += LengthA;
1718 A.Last = Tok;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001719 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001720 }
1721
Daniel Jasper97b89482013-03-13 07:49:51 +00001722 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001723 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1724 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1725 Ranges[i].getBegin()) &&
1726 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1727 Range.getBegin()))
1728 return true;
1729 }
1730 return false;
1731 }
1732
1733 bool touchesLine(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001734 const FormatToken *First = TheLine.First;
1735 const FormatToken *Last = TheLine.Last;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001736 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001737 First->WhitespaceRange.getBegin().getLocWithOffset(
1738 First->LastNewlineOffset),
Alexander Kornienkoee4ca9b2013-06-07 17:45:07 +00001739 Last->Tok.getLocation().getLocWithOffset(Last->TokenText.size() - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001740 return touchesRanges(LineRange);
1741 }
1742
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001743 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1744 std::vector<AnnotatedLine>::iterator E) {
1745 for (; I != E; ++I) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001746 if (I->First->HasUnescapedNewline)
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001747 return false;
1748 if (touchesLine(*I))
1749 return true;
1750 }
1751 return false;
1752 }
1753
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001754 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001755 const FormatToken *First = TheLine.First;
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001756 CharSourceRange LineRange = CharSourceRange::getCharRange(
Manuel Klimek5c24cca2013-05-23 10:56:37 +00001757 First->WhitespaceRange.getBegin(),
1758 First->WhitespaceRange.getBegin().getLocWithOffset(
1759 First->LastNewlineOffset));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001760 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001761 }
1762
1763 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001764 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001765 }
1766
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001767 /// \brief Add a new line and the required indent before the first Token
1768 /// of the \c UnwrappedLine if there was no structural parsing error.
1769 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001770 void formatFirstToken(const FormatToken &RootToken,
1771 const FormatToken *PreviousToken, unsigned Indent,
Manuel Klimek4fe43002013-05-22 12:51:29 +00001772 bool InPPDirective) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001773 unsigned Newlines =
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001774 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Daniel Jasper1027c6e2013-06-03 16:16:41 +00001775 // Remove empty lines before "}" where applicable.
1776 if (RootToken.is(tok::r_brace) &&
1777 (!RootToken.Next ||
1778 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1779 Newlines = std::min(Newlines, 1u);
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001780 if (Newlines == 0 && !RootToken.IsFirst)
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001781 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001782
Manuel Klimek4fe43002013-05-22 12:51:29 +00001783 // Insert extra new line before access specifiers.
1784 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001785 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
Manuel Klimek4fe43002013-05-22 12:51:29 +00001786 ++Newlines;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001787
Manuel Klimek6e6310e2013-05-29 14:47:47 +00001788 Whitespaces.replaceWhitespace(
1789 RootToken, Newlines, Indent, Indent,
1790 InPPDirective && !RootToken.HasUnescapedNewline);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001791 }
1792
Daniel Jasperf7935112012-12-03 18:12:45 +00001793 FormatStyle Style;
1794 Lexer &Lex;
1795 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001796 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001797 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001798 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkoffcc0102013-06-05 14:09:10 +00001799
1800 encoding::Encoding Encoding;
Daniel Jasperb10cbc42013-07-10 14:02:49 +00001801 bool BinPackInconclusiveFunctions;
Daniel Jasperf7935112012-12-03 18:12:45 +00001802};
1803
Craig Topperaf35e852013-06-30 22:29:28 +00001804} // end anonymous namespace
1805
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001806tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1807 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001808 std::vector<CharSourceRange> Ranges) {
1809 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001810 return formatter.format();
1811}
1812
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001813tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1814 std::vector<tooling::Range> Ranges,
1815 StringRef FileName) {
1816 FileManager Files((FileSystemOptions()));
1817 DiagnosticsEngine Diagnostics(
1818 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1819 new DiagnosticOptions);
1820 SourceManager SourceMgr(Diagnostics, Files);
1821 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1822 const clang::FileEntry *Entry =
1823 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1824 SourceMgr.overrideFileContents(Entry, Buf);
1825 FileID ID =
1826 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
Alexander Kornienko1e808872013-06-28 12:51:24 +00001827 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
1828 getFormattingLangOpts(Style.Standard));
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001829 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1830 std::vector<CharSourceRange> CharRanges;
1831 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1832 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1833 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1834 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1835 }
1836 return reformat(Style, Lex, SourceMgr, CharRanges);
1837}
1838
Alexander Kornienko1e808872013-06-28 12:51:24 +00001839LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001840 LangOptions LangOpts;
1841 LangOpts.CPlusPlus = 1;
Alexander Kornienko1e808872013-06-28 12:51:24 +00001842 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001843 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001844 LangOpts.Bool = 1;
1845 LangOpts.ObjC1 = 1;
1846 LangOpts.ObjC2 = 1;
1847 return LangOpts;
1848}
1849
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001850} // namespace format
1851} // namespace clang