blob: b64437046f62f07a0603e2a269ea6022fce661a3 [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]);
63 if (Style == clang::format::getPredefinedStyle(StyleName)) {
64 IO.mapOptional("# BasedOnStyle", StyleName);
65 break;
66 }
67 }
68 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000069 StringRef BasedOnStyle;
70 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000071 if (!BasedOnStyle.empty())
72 Style = clang::format::getPredefinedStyle(BasedOnStyle);
73 }
74
75 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
76 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
77 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
78 Style.AllowAllParametersOfDeclarationOnNextLine);
79 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
80 Style.AllowShortIfStatementsOnASingleLine);
81 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
82 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
83 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
84 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
85 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
86 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
87 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
88 IO.mapOptional("ObjCSpaceBeforeProtocolList",
89 Style.ObjCSpaceBeforeProtocolList);
90 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
91 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
92 Style.PenaltyReturnTypeOnItsOwnLine);
93 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
94 IO.mapOptional("SpacesBeforeTrailingComments",
95 Style.SpacesBeforeTrailingComments);
96 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +000097 IO.mapOptional("IndentWidth", Style.IndentWidth);
Manuel Klimekb9eae4c2013-05-13 09:22:11 +000098 IO.mapOptional("UseTab", Style.UseTab);
Manuel Klimeka8eb9142013-05-13 12:51:40 +000099 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
Alexander Kornienkod6538332013-05-07 15:32:14 +0000100 }
101};
102}
103}
104
Daniel Jasperf7935112012-12-03 18:12:45 +0000105namespace clang {
106namespace format {
107
Daniel Jasperf7935112012-12-03 18:12:45 +0000108FormatStyle getLLVMStyle() {
109 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000110 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000111 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000112 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000113 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000114 LLVMStyle.BinPackParameters = true;
115 LLVMStyle.ColumnLimit = 80;
116 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
117 LLVMStyle.DerivePointerBinding = false;
118 LLVMStyle.IndentCaseLabels = false;
119 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000120 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000121 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000122 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000123 LLVMStyle.PointerBindsToType = false;
124 LLVMStyle.SpacesBeforeTrailingComments = 1;
125 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000126 LLVMStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000127 LLVMStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000128 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000129 return LLVMStyle;
130}
131
132FormatStyle getGoogleStyle() {
133 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000134 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000135 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000136 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000137 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000138 GoogleStyle.BinPackParameters = true;
139 GoogleStyle.ColumnLimit = 80;
140 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
141 GoogleStyle.DerivePointerBinding = true;
142 GoogleStyle.IndentCaseLabels = true;
143 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000144 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000145 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000146 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000147 GoogleStyle.PointerBindsToType = true;
148 GoogleStyle.SpacesBeforeTrailingComments = 2;
149 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000150 GoogleStyle.IndentWidth = 2;
Manuel Klimekb9eae4c2013-05-13 09:22:11 +0000151 GoogleStyle.UseTab = false;
Manuel Klimeka8eb9142013-05-13 12:51:40 +0000152 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
Daniel Jasperf7935112012-12-03 18:12:45 +0000153 return GoogleStyle;
154}
155
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000156FormatStyle getChromiumStyle() {
157 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000158 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000159 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000160 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000161 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
162 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000163 return ChromiumStyle;
164}
165
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000166FormatStyle getMozillaStyle() {
167 FormatStyle MozillaStyle = getLLVMStyle();
168 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
169 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
170 MozillaStyle.DerivePointerBinding = true;
171 MozillaStyle.IndentCaseLabels = true;
172 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
173 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
174 MozillaStyle.PointerBindsToType = true;
175 return MozillaStyle;
176}
177
Alexander Kornienkod6538332013-05-07 15:32:14 +0000178FormatStyle getPredefinedStyle(StringRef Name) {
179 if (Name.equals_lower("llvm"))
180 return getLLVMStyle();
181 if (Name.equals_lower("chromium"))
182 return getChromiumStyle();
183 if (Name.equals_lower("mozilla"))
184 return getMozillaStyle();
185 if (Name.equals_lower("google"))
186 return getGoogleStyle();
187
188 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
189 return getGoogleStyle();
190}
191
192llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
193 llvm::yaml::Input Input(Text);
194 Input >> *Style;
195 return Input.error();
196}
197
198std::string configurationAsText(const FormatStyle &Style) {
199 std::string Text;
200 llvm::raw_string_ostream Stream(Text);
201 llvm::yaml::Output Output(Stream);
202 // We use the same mapping method for input and output, so we need a non-const
203 // reference here.
204 FormatStyle NonConstStyle = Style;
205 Output << NonConstStyle;
Alexander Kornienko9a38ec22013-05-13 12:56:35 +0000206 return Stream.str();
Alexander Kornienkod6538332013-05-07 15:32:14 +0000207}
208
Daniel Jasperacc33662013-02-08 08:22:00 +0000209// Returns the length of everything up to the first possible line break after
210// the ), ], } or > matching \c Tok.
211static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
212 if (Tok.MatchingParen == NULL)
213 return 0;
214 AnnotatedToken *End = Tok.MatchingParen;
215 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
216 End = &End->Children[0];
217 }
218 return End->TotalLength - Tok.TotalLength + 1;
219}
220
Daniel Jasperf7935112012-12-03 18:12:45 +0000221class UnwrappedLineFormatter {
222public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000223 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000224 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000225 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000226 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000227 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000228 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000229 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000230
Manuel Klimek1abf7892013-01-04 23:34:14 +0000231 /// \brief Formats an \c UnwrappedLine.
232 ///
233 /// \returns The column after the last token in the last line of the
234 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000235 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000236 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000237 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000238 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000239 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000240 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000241 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000242 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000243 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000244 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000245 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000246 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000247
248 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000249 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000250
Daniel Jasper4b866272013-02-01 11:00:45 +0000251 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000252 unsigned ColumnLimit = Style.ColumnLimit;
253 if (NextLine && NextLine->InPPDirective &&
254 !NextLine->First.FormatTok.HasUnescapedNewline)
255 ColumnLimit = getColumnLimit();
256 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000257 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000258 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000259 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000260 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000261 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000262
Daniel Jasperacc33662013-02-08 08:22:00 +0000263 // If the ObjC method declaration does not fit on a line, we should format
264 // it with one arg per line.
265 if (Line.Type == LT_ObjCMethodDecl)
266 State.Stack.back().BreakBeforeParameter = true;
267
Daniel Jasper4b866272013-02-01 11:00:45 +0000268 // Find best solution in solution space.
269 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000270 }
271
272private:
Manuel Klimek24998102013-01-16 14:55:28 +0000273 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
274 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000275 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000276 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000277 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000278 }
279
Daniel Jasper337816e2013-01-11 10:22:12 +0000280 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000281 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000282 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000283 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
284 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000285 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000286 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
287 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000288 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000289
Daniel Jasperf7935112012-12-03 18:12:45 +0000290 /// \brief The position to which a specific parenthesis level needs to be
291 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000292 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000293
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294 /// \brief The position of the last space on each level.
295 ///
296 /// Used e.g. to break like:
297 /// functionCall(Parameter, otherCall(
298 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000299 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000300
Daniel Jaspere9de2602012-12-06 09:56:08 +0000301 /// \brief The position the first "<<" operator encountered on each level.
302 ///
303 /// Used to align "<<" operators. 0 if no such operator has been encountered
304 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000305 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000306
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000307 /// \brief Whether a newline needs to be inserted before the block's closing
308 /// brace.
309 ///
310 /// We only want to insert a newline before the closing brace if there also
311 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000312 bool BreakBeforeClosingBrace;
313
Daniel Jasperca6623b2013-01-28 12:45:14 +0000314 /// \brief The column of a \c ? in a conditional expression;
315 unsigned QuestionColumn;
316
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000317 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
318 /// lines, in this context.
319 bool AvoidBinPacking;
320
321 /// \brief Break after the next comma (or all the commas in this context if
322 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000323 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000324
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000325 /// \brief Line breaking in this context would break a formatting rule.
326 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000327
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000328 /// \brief The position of the colon in an ObjC method declaration/call.
329 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000330
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000331 /// \brief The start of the most recent function in a builder-type call.
332 unsigned StartOfFunctionCall;
333
Daniel Jasperc238c872013-04-02 14:33:13 +0000334 /// \brief If a nested name specifier was broken over multiple lines, this
335 /// contains the start column of the second line. Otherwise 0.
336 unsigned NestedNameSpecifierContinuation;
337
338 /// \brief If a call expression was broken over multiple lines, this
339 /// contains the start column of the second line. Otherwise 0.
340 unsigned CallContinuation;
341
Daniel Jaspera628c982013-04-03 13:36:17 +0000342 /// \brief The column of the first variable name in a variable declaration.
343 ///
344 /// Used to align further variables if necessary.
345 unsigned VariablePos;
346
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000347 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
348 ///
349 /// Does not need to be considered for memoization / the comparison function
350 /// as otherwise identical states will have the same fake/non-fake
351 /// \c ParenStates.
352 bool ForFakeParenthesis;
353
Daniel Jasper337816e2013-01-11 10:22:12 +0000354 bool operator<(const ParenState &Other) const {
355 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000356 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000357 if (LastSpace != Other.LastSpace)
358 return LastSpace < Other.LastSpace;
359 if (FirstLessLess != Other.FirstLessLess)
360 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000361 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
362 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000363 if (QuestionColumn != Other.QuestionColumn)
364 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000365 if (AvoidBinPacking != Other.AvoidBinPacking)
366 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000367 if (BreakBeforeParameter != Other.BreakBeforeParameter)
368 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000369 if (NoLineBreak != Other.NoLineBreak)
370 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000371 if (ColonPos != Other.ColonPos)
372 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000373 if (StartOfFunctionCall != Other.StartOfFunctionCall)
374 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000375 if (CallContinuation != Other.CallContinuation)
376 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000377 if (VariablePos != Other.VariablePos)
378 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000379 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000380 }
381 };
382
383 /// \brief The current state when indenting a unwrapped line.
384 ///
385 /// As the indenting tries different combinations this is copied by value.
386 struct LineState {
387 /// \brief The number of used columns in the current line.
388 unsigned Column;
389
390 /// \brief The token that needs to be next formatted.
391 const AnnotatedToken *NextToken;
392
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000393 /// \brief \c true if this line contains a continued for-loop section.
394 bool LineContainsContinuedForLoopSection;
395
Daniel Jasper400adc62013-02-08 15:28:42 +0000396 /// \brief The level of nesting inside (), [], <> and {}.
397 unsigned ParenLevel;
398
Daniel Jasper40c36c52013-02-18 11:05:07 +0000399 /// \brief The \c ParenLevel at the start of this line.
400 unsigned StartOfLineLevel;
401
Manuel Klimek02f640a2013-02-20 15:25:48 +0000402 /// \brief The start column of the string literal, if we're in a string
403 /// literal sequence, 0 otherwise.
404 unsigned StartOfStringLiteral;
405
Daniel Jasper337816e2013-01-11 10:22:12 +0000406 /// \brief A stack keeping track of properties applying to parenthesis
407 /// levels.
408 std::vector<ParenState> Stack;
409
410 /// \brief Comparison operator to be able to used \c LineState in \c map.
411 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000412 if (NextToken != Other.NextToken)
413 return NextToken < Other.NextToken;
414 if (Column != Other.Column)
415 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000416 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000417 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000418 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000419 if (ParenLevel != Other.ParenLevel)
420 return ParenLevel < Other.ParenLevel;
421 if (StartOfLineLevel != Other.StartOfLineLevel)
422 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000423 if (StartOfStringLiteral != Other.StartOfStringLiteral)
424 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000425 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 }
427 };
428
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000429 /// \brief Appends the next token to \p State and updates information
430 /// necessary for indentation.
431 ///
432 /// Puts the token on the current line if \p Newline is \c true and adds a
433 /// line break and necessary indentation otherwise.
434 ///
435 /// If \p DryRun is \c false, also creates and stores the required
436 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000437 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000438 const AnnotatedToken &Current = *State.NextToken;
439 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000440
Daniel Jasper291f9362013-03-20 15:58:10 +0000441 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000442 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
443 State.NextToken->FormatTok.TokenLength;
444 if (State.NextToken->Children.empty())
445 State.NextToken = NULL;
446 else
447 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000448 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000449 }
450
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000451 // If we are continuing an expression, we want to indent an extra 4 spaces.
452 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000453 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000455 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000456 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000457 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000458 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000459 State.StartOfStringLiteral != 0) {
460 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000461 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000462 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000463 State.Stack.back().FirstLessLess != 0) {
464 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000465 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000466 if (State.Stack.back().CallContinuation == 0) {
467 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000468 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000469 } else {
470 State.Column = State.Stack.back().CallContinuation;
471 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000472 } else if (Current.Type == TT_ConditionalExpr) {
473 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000474 } else if (Previous.is(tok::comma) &&
475 State.Stack.back().VariablePos != 0) {
476 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000477 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000478 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
479 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000480 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000481 } else if (Current.Type == TT_ObjCSelectorName) {
482 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
483 State.Column =
484 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
485 } else {
486 State.Column = State.Stack.back().Indent;
487 State.Stack.back().ColonPos =
488 State.Column + Current.FormatTok.TokenLength;
489 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000490 } else if (Current.Type == TT_StartOfName ||
491 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000492 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000493 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000494 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000495 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000496 // Ensure that we fall back to indenting 4 spaces instead of just
497 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000498 if (State.Column == FirstIndent)
499 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000500 }
501
Daniel Jasper54a86022013-02-15 11:07:25 +0000502 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000503 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000504 if ((Previous.isOneOf(tok::comma, tok::semi) &&
505 !State.Stack.back().AvoidBinPacking) ||
506 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000507 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000508 if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
509 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000510
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000511 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000512 unsigned NewLines = 1;
513 if (Current.Type == TT_LineComment)
514 NewLines =
515 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
516 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000517 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000518 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000519 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000520 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000521 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000522 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000523 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000524
Daniel Jasper400adc62013-02-08 15:28:42 +0000525 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000526 if (Current.isOneOf(tok::arrow, tok::period))
527 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000528 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000529
530 // Any break on this level means that the parent level has been broken
531 // and we need to avoid bin packing there.
532 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
533 State.Stack[i].BreakBeforeParameter = true;
534 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000535 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
536 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperc6fbc212013-05-15 09:35:08 +0000537 TokenBefore->Type != TT_TemplateCloser &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000538 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000539 State.Stack.back().BreakBeforeParameter = true;
540
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000541 // If we break after {, we should also break before the corresponding }.
542 if (Previous.is(tok::l_brace))
543 State.Stack.back().BreakBeforeClosingBrace = true;
544
545 if (State.Stack.back().AvoidBinPacking) {
546 // If we are breaking after '(', '{', '<', this is not bin packing
547 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper571f1af2013-05-14 20:39:56 +0000548 if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
549 Previous.Type == TT_BinaryOperator) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000550 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
551 Line.MustBeDeclaration))
552 State.Stack.back().BreakBeforeParameter = true;
553 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000554 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000555 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000556 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
557 State.Stack.back().VariablePos == 0) {
558 State.Stack.back().VariablePos = State.Column;
559 // Move over * and & if they are bound to the variable name.
560 const AnnotatedToken *Tok = &Previous;
561 while (Tok &&
562 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
563 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
564 if (Tok->SpacesRequiredBefore != 0)
565 break;
566 Tok = Tok->Parent;
567 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000568 if (Previous.PartOfMultiVariableDeclStmt)
569 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
570 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000571
Daniel Jaspereef30492013-02-11 12:36:37 +0000572 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000573
Daniel Jasperf7935112012-12-03 18:12:45 +0000574 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000575 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000576
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000577 if (Current.Type == TT_ObjCSelectorName &&
578 State.Stack.back().ColonPos == 0) {
579 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000580 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000581 State.Stack.back().ColonPos =
582 State.Stack.back().Indent + Current.LongestObjCSelectorName;
583 else
584 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000585 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000586 }
587
Daniel Jasperc04baae2013-04-10 09:49:49 +0000588 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000589 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000590 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000591 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
592 State.Stack.back().AvoidBinPacking)
593 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000594
Daniel Jaspere9de2602012-12-06 09:56:08 +0000595 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000596 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000597 // Treat the condition inside an if as if it was a second function
598 // parameter, i.e. let nested calls have an indent of 4.
599 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000600 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000601 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000602 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000603 Previous.Type == TT_ConditionalExpr ||
604 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000605 getPrecedence(Previous) != prec::Assignment)
606 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000607 else if (Previous.Type == TT_InheritanceColon)
608 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000609 else if (Previous.opensScope() && !Current.FakeLParens.empty())
610 // If this function has multiple parameters or a binary expression
611 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000612 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000613 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000614
Manuel Klimek1998ea22013-02-20 10:15:13 +0000615 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000616 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000617
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000618 /// \brief Mark the next token as consumed in \p State and modify its stacks
619 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000620 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000621 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000622 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000623
Daniel Jaspereead02b2013-02-14 08:42:54 +0000624 if (Current.Type == TT_InheritanceColon)
625 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000626 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
627 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000628 if (Current.is(tok::question))
629 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000630 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000631 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
632 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000633 Current.LastInChainOfCalls ? 0 : State.Column +
634 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000635 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000636 // Indent 2 from the column, so:
637 // SomeClass::SomeClass()
638 // : First(...), ...
639 // Next(...)
640 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000641 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000642 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
643 State.Stack.back().AvoidBinPacking = true;
644 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000645 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000646
Daniel Jasper6bee6822013-04-08 20:33:42 +0000647 // If return returns a binary expression, align after it.
648 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
649 State.Stack.back().LastSpace = State.Column + 7;
650
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000651 // In ObjC method declaration we align on the ":" of parameters, but we need
652 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000653 if (Current.Type == TT_ObjCMethodSpecifier)
654 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000655
Daniel Jasper400adc62013-02-08 15:28:42 +0000656 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000657 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
658 // Don't add extra indentation for the first fake parenthesis after
659 // 'return', assignements or opening <({[. The indentation for these cases
660 // is special cased.
661 bool SkipFirstExtraIndent =
662 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000663 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000664 getPrecedence(*Previous) == prec::Assignment));
665 for (SmallVector<prec::Level, 4>::const_reverse_iterator
666 I = Current.FakeLParens.rbegin(),
667 E = Current.FakeLParens.rend();
668 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000669 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000670 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000671 NewParenState.Indent =
672 std::max(std::max(State.Column, NewParenState.Indent),
673 State.Stack.back().LastSpace);
674
675 // Always indent conditional expressions. Never indent expression where
676 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
677 // prec::Assignment) as those have different indentation rules. Indent
678 // other expression, unless the indentation needs to be skipped.
679 if (*I == prec::Conditional ||
680 (!SkipFirstExtraIndent && *I > prec::Assignment))
681 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000682 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000683 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000684 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000685 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000686 }
687
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000688 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000689 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000690 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000691 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000692 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000693 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000694 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000695 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000696 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000697 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000698 NewIndent =
699 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000700 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000701 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000702
703 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
704 // This parenthesis was the last token possibly making use of Indent and
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000705 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000706 // better memoization results.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000707 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
708 State.Stack[i].Indent = 0;
709 State.Stack[i].LastSpace = 0;
710 if (!State.Stack[i].ForFakeParenthesis)
711 break;
712 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000713 }
714
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000715 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
716 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000717 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000718 }
719
Daniel Jasperacc33662013-02-08 08:22:00 +0000720 // If this '[' opens an ObjC call, determine whether all parameters fit into
721 // one line and put one per line if they don't.
722 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
723 Current.MatchingParen != NULL) {
724 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
725 State.Stack.back().BreakBeforeParameter = true;
726 }
727
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000728 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000729 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000730 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000731 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
732 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000733 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000734 --State.ParenLevel;
735 }
736
737 // Remove scopes created by fake parenthesis.
738 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000739 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000740 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000741 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000743
Daniel Jasper47a04442013-05-13 20:50:15 +0000744 if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000745 State.StartOfStringLiteral = State.Column;
Daniel Jasper47a04442013-05-13 20:50:15 +0000746 } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
747 tok::string_literal)) {
Daniel Jasper7dd22c51b2013-05-16 04:26:02 +0000748 State.StartOfStringLiteral = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000749 }
750
Manuel Klimek1998ea22013-02-20 10:15:13 +0000751 State.Column += Current.FormatTok.TokenLength;
752
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000753 if (State.NextToken->Children.empty())
754 State.NextToken = NULL;
755 else
756 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000757
Manuel Klimek1998ea22013-02-20 10:15:13 +0000758 return breakProtrudingToken(Current, State, DryRun);
759 }
760
761 /// \brief If the current token sticks out over the end of the line, break
762 /// it if possible.
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000763 ///
764 /// \returns An extra penalty if a token was broken, otherwise 0.
765 ///
766 /// Note that the penalty of the token protruding the allowed line length is
767 /// already handled in \c addNextStateToQueue; the returned penalty will only
768 /// cover the cost of the additional line breaks.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000769 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000770 bool DryRun,
771 unsigned UnbreakableTailLength = 0) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000772 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000773 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
774 UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000775 if (Current.is(tok::string_literal)) {
776 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000777 const char *LiteralData = SourceMgr.getCharacterData(
778 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000779 if (!LiteralData || *LiteralData != '"')
780 return 0;
781
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000782 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
783 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000784 } else if (Current.Type == TT_BlockComment) {
785 BreakableBlockComment *BBC =
786 new BreakableBlockComment(SourceMgr, Current, StartColumn);
787 if (!DryRun)
788 BBC->alignLines(Whitespaces);
789 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000790 } else if (Current.Type == TT_LineComment &&
791 (Current.Parent == NULL ||
792 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000793 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000794 } else {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000795 // If a token that we cannot breaks protrudes, it means we were unable to
796 // break a sequence of tokens due to disallowed breaks between the tokens.
797 // Thus, we recursively search backwards to try to find a breakable token.
798 if (State.Column <= getColumnLimit() ||
799 Current.CanBreakBefore || !Current.Parent)
800 return 0;
801 return breakProtrudingToken(
802 *Current.Parent, State, DryRun,
803 UnbreakableTailLength + Current.FormatTok.TokenLength);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000804 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000805 if (UnbreakableTailLength >= getColumnLimit())
806 return 0;
807 unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000808
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000809 bool BreakInserted = false;
810 unsigned Penalty = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000811 unsigned PositionAfterLastLineInToken = 0;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000812 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
813 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000814 unsigned TailOffset = 0;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000815 unsigned RemainingTokenLength =
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000816 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000817 while (RemainingTokenLength > RemainingSpace) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000818 BreakableToken::Split Split =
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000819 Token->getSplit(LineIndex, TailOffset, RemainingSpace);
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000820 if (Split.first == StringRef::npos)
821 break;
822 assert(Split.first != 0);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000823 unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000824 LineIndex, TailOffset + Split.first + Split.second);
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000825 if (NewRemainingTokenLength >= RemainingTokenLength)
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000826 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000827 if (!DryRun) {
828 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
829 Whitespaces);
830 }
831 TailOffset += Split.first + Split.second;
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000832 RemainingTokenLength = NewRemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000833 Penalty += Style.PenaltyExcessCharacter;
834 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000835 }
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000836 PositionAfterLastLineInToken = RemainingTokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000837 if (!DryRun) {
838 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
839 }
840 }
841
842 if (BreakInserted) {
Manuel Klimek5ecb5fd2013-05-14 09:04:24 +0000843 State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000844 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
845 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000846 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000847 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000848 return Penalty;
849 }
850
Daniel Jasper2df93312013-01-09 10:16:05 +0000851 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000852 // In preprocessor directives reserve two chars for trailing " \"
853 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000854 }
855
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000856 /// \brief An edge in the solution space from \c Previous->State to \c State,
857 /// inserting a newline dependent on the \c NewLine.
858 struct StateNode {
859 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000860 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000861 LineState State;
862 bool NewLine;
863 StateNode *Previous;
864 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000865
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000866 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
867 ///
868 /// In case of equal penalties, we want to prefer states that were inserted
869 /// first. During state generation we make sure that we insert states first
870 /// that break the line as late as possible.
871 typedef std::pair<unsigned, unsigned> OrderedPenalty;
872
873 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
874 /// \c State has the given \c OrderedPenalty.
875 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
876
877 /// \brief The BFS queue type.
878 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
879 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000880
881 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000882 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000883 /// This implements a variant of Dijkstra's algorithm on the graph that spans
884 /// the solution space (\c LineStates are the nodes). The algorithm tries to
885 /// find the shortest path (the one with lowest penalty) from \p InitialState
886 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000887 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000888 std::set<LineState> Seen;
889
Daniel Jasper4b866272013-02-01 11:00:45 +0000890 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000891 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000892 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
893 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
894 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000895
896 // While not empty, take first element and follow edges.
897 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000898 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000899 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000900 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000901 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000902 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000903 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000904 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000905
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 if (!Seen.insert(Node->State).second)
907 // State already examined with lower penalty.
908 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000909
Manuel Klimekaf491072013-02-13 10:54:19 +0000910 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
911 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000912 }
913
914 if (Queue.empty())
915 // We were unable to find a solution, do nothing.
916 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000917 return 0;
918
Daniel Jasper4b866272013-02-01 11:00:45 +0000919 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000920 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000921 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
922 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000923
Daniel Jasper4b866272013-02-01 11:00:45 +0000924 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000925 return Queue.top().second->State.Column;
926 }
927
928 void reconstructPath(LineState &State, StateNode *Current) {
929 // FIXME: This recursive implementation limits the possible number
930 // of tokens per line if compiled into a binary with small stack space.
931 // To become more independent of stack frame limitations we would need
932 // to also change the TokenAnnotator.
933 if (Current->Previous == NULL)
934 return;
935 reconstructPath(State, Current->Previous);
936 DEBUG({
937 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000938 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000939 << "Penalty for splitting before "
940 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
941 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000942 }
943 });
944 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 }
946
Manuel Klimekaf491072013-02-13 10:54:19 +0000947 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000948 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000949 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000950 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000951 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
952 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000953 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000954 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000955 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000956 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000957 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000958 Penalty += PreviousNode->State.NextToken->SplitPenalty;
959
960 StateNode *Node = new (Allocator.Allocate())
961 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000962 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000963 if (Node->State.Column > getColumnLimit()) {
964 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000965 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000966 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000967
968 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
969 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000970 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000971
Daniel Jasper4b866272013-02-01 11:00:45 +0000972 /// \brief Returns \c true, if a line break after \p State is allowed.
973 bool canBreak(const LineState &State) {
974 if (!State.NextToken->CanBreakBefore &&
975 !(State.NextToken->is(tok::r_brace) &&
976 State.Stack.back().BreakBeforeClosingBrace))
977 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000978 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000979 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000980
Daniel Jasper4b866272013-02-01 11:00:45 +0000981 /// \brief Returns \c true, if a line break after \p State is mandatory.
982 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000983 const AnnotatedToken &Current = *State.NextToken;
984 const AnnotatedToken &Previous = *Current.Parent;
985 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +0000986 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000987 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +0000988 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000989 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +0000990 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000991 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
992 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000993 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000994 !Current.isTrailingComment() &&
995 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000996 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000997
998 // If we need to break somewhere inside the LHS of a binary expression, we
999 // should also break after the operator.
1000 if (Previous.Type == TT_BinaryOperator &&
1001 !Previous.isOneOf(tok::lessless, tok::question) &&
1002 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001003 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001004 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001005
1006 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1007 // out whether it is the first parameter. Clean this up.
1008 if (Current.Type == TT_ObjCSelectorName &&
1009 Current.LongestObjCSelectorName == 0 &&
1010 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +00001011 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001012 if ((Current.Type == TT_CtorInitializerColon ||
1013 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +00001014 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +00001015
Daniel Jasper9b334242013-03-15 14:57:30 +00001016 // This prevents breaks like:
1017 // ...
1018 // SomeParameter, OtherParameter).DoSomething(
1019 // ...
1020 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +00001021 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +00001022 getRemainingLength(State) + State.Column > getColumnLimit() &&
1023 State.ParenLevel < State.StartOfLineLevel)
1024 return true;
Daniel Jasperc6fbc212013-05-15 09:35:08 +00001025
1026 if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
1027 State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
1028 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001029 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 }
1031
Daniel Jasper9b334242013-03-15 14:57:30 +00001032 // Returns the total number of columns required for the remaining tokens.
1033 unsigned getRemainingLength(const LineState &State) {
1034 if (State.NextToken && State.NextToken->Parent)
1035 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1036 return 0;
1037 }
1038
Daniel Jasperf7935112012-12-03 18:12:45 +00001039 FormatStyle Style;
1040 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001041 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001042 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001043 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001044 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001045
1046 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1047 QueueType Queue;
1048 // Increasing count of \c StateNode items we have created. This is used
1049 // to create a deterministic order independent of the container.
1050 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001051};
1052
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001053class LexerBasedFormatTokenSource : public FormatTokenSource {
1054public:
1055 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001056 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001057 IdentTable(Lex.getLangOpts()) {
1058 Lex.SetKeepWhitespaceMode(true);
1059 }
1060
1061 virtual FormatToken getNextToken() {
1062 if (GreaterStashed) {
1063 FormatTok.NewlinesBefore = 0;
1064 FormatTok.WhiteSpaceStart =
1065 FormatTok.Tok.getLocation().getLocWithOffset(1);
1066 FormatTok.WhiteSpaceLength = 0;
1067 GreaterStashed = false;
1068 return FormatTok;
1069 }
1070
1071 FormatTok = FormatToken();
1072 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001073 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001074 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001075 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1076 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001077
1078 // Consume and record whitespace until we find a significant token.
1079 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001080 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001081 if (Newlines > 0)
1082 FormatTok.LastNewlineOffset =
1083 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001084 unsigned EscapedNewlines = Text.count("\\\n");
1085 FormatTok.NewlinesBefore += Newlines;
1086 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001087 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1088
1089 if (FormatTok.Tok.is(tok::eof))
1090 return FormatTok;
1091 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001092 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001093 }
Manuel Klimekef920692013-01-07 07:56:50 +00001094
1095 // Now FormatTok is the next non-whitespace token.
1096 FormatTok.TokenLength = Text.size();
1097
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001098 if (FormatTok.Tok.is(tok::comment)) {
1099 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1100 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1101 }
1102
Manuel Klimek1abf7892013-01-04 23:34:14 +00001103 // In case the token starts with escaped newlines, we want to
1104 // take them into account as whitespace - this pattern is quite frequent
1105 // in macro definitions.
1106 // FIXME: What do we want to do with other escaped spaces, and escaped
1107 // spaces or newlines in the middle of tokens?
1108 // FIXME: Add a more explicit test.
1109 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001110 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001111 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001112 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001113 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001114 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001115 }
1116
1117 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001118 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001119 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001120 FormatTok.Tok.setKind(Info.getTokenID());
1121 }
1122
1123 if (FormatTok.Tok.is(tok::greatergreater)) {
1124 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001125 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001126 GreaterStashed = true;
1127 }
1128
1129 return FormatTok;
1130 }
1131
Nico Weber29f9dea2013-02-11 15:32:15 +00001132 IdentifierTable &getIdentTable() { return IdentTable; }
1133
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001134private:
1135 FormatToken FormatTok;
1136 bool GreaterStashed;
1137 Lexer &Lex;
1138 SourceManager &SourceMgr;
1139 IdentifierTable IdentTable;
1140
1141 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001142 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001143 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1144 Tok.getLength());
1145 }
1146};
1147
Daniel Jasperf7935112012-12-03 18:12:45 +00001148class Formatter : public UnwrappedLineConsumer {
1149public:
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001150 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001151 const std::vector<CharSourceRange> &Ranges)
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001152 : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001153 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001154
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001155 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001156
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001157 tooling::Replacements format() {
1158 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001159 UnwrappedLineParser Parser(Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001160 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001161 unsigned PreviousEndOfLineColumn = 0;
1162 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1163 Tokens.getIdentTable().get("in"));
1164 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1165 Annotator.annotate(AnnotatedLines[i]);
1166 }
1167 deriveLocalStyle();
1168 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1169 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1170 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001171
1172 // Adapt level to the next line if this is a comment.
1173 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001174 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001175 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1176 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1177 AnnotatedLines[i].First.Children.empty())
1178 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1179 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001180 NextNoneCommentLine =
1181 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1182 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001183 }
1184
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001185 std::vector<int> IndentForLevel;
1186 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001187 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001188 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001189 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1190 E = AnnotatedLines.end();
1191 I != E; ++I) {
1192 const AnnotatedLine &TheLine = *I;
1193 const FormatToken &FirstTok = TheLine.First.FormatTok;
1194 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001195
1196 // Check whether this line is part of a formatted preprocessor directive.
1197 if (FirstTok.HasUnescapedNewline)
1198 FormatPPDirective = false;
1199 if (!FormatPPDirective && TheLine.InPPDirective &&
1200 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1201 FormatPPDirective = true;
1202
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001203 // Determine indent and try to merge multiple unwrapped lines.
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001204 while (IndentForLevel.size() <= TheLine.Level)
1205 IndentForLevel.push_back(-1);
1206 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001207 unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
1208 if (static_cast<int>(Indent) + Offset >= 0)
1209 Indent += Offset;
1210 tryFitMultipleLinesInOne(Indent, I, E);
1211
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001212 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001213 if (TheLine.First.is(tok::eof)) {
1214 if (PreviousLineWasTouched) {
1215 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1216 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001217 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001218 }
1219 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001220 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001221 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001222 if (FirstTok.WhiteSpaceStart.isValid() &&
1223 // Insert a break even if there is a structural error in case where
1224 // we break apart a line consisting of multiple unwrapped lines.
1225 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001226 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1227 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001228 } else {
1229 Indent = LevelIndent =
1230 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001231 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001232 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001233 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001234 PreviousEndOfLineColumn =
1235 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1236 IndentForLevel[TheLine.Level] = LevelIndent;
1237 PreviousLineWasTouched = true;
1238 } else {
1239 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001240 unsigned LevelIndent =
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001241 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Daniel Jasper12f9d8e2013-05-14 09:30:02 +00001242 // Remove trailing whitespace of the previous line if it was touched.
1243 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1244 formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
1245 TheLine.InPPDirective, PreviousEndOfLineColumn);
1246
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001247 if (static_cast<int>(LevelIndent) - Offset >= 0)
1248 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001249 if (TheLine.First.isNot(tok::comment))
1250 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001251 }
1252 // If we did not reformat this unwrapped line, the column at the end of
1253 // the last token is unchanged - thus, we can calculate the end of the
1254 // last token.
1255 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1256 PreviousEndOfLineColumn =
1257 SourceMgr.getSpellingColumnNumber(LastLoc) +
1258 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1259 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001260 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001261 Whitespaces.addUntouchableComment(
1262 SourceMgr.getSpellingColumnNumber(
1263 TheLine.Last->FormatTok.Tok.getLocation()) -
1264 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001265 else
1266 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001267 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001268 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001269 }
1270 return Whitespaces.generateReplacements();
1271 }
1272
1273private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001274 void deriveLocalStyle() {
1275 unsigned CountBoundToVariable = 0;
1276 unsigned CountBoundToType = 0;
1277 bool HasCpp03IncompatibleFormat = false;
1278 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1279 if (AnnotatedLines[i].First.Children.empty())
1280 continue;
1281 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1282 while (!Tok->Children.empty()) {
1283 if (Tok->Type == TT_PointerOrReference) {
1284 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1285 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1286 if (SpacesBefore && !SpacesAfter)
1287 ++CountBoundToVariable;
1288 else if (!SpacesBefore && SpacesAfter)
1289 ++CountBoundToType;
1290 }
1291
Daniel Jasper400adc62013-02-08 15:28:42 +00001292 if (Tok->Type == TT_TemplateCloser &&
1293 Tok->Parent->Type == TT_TemplateCloser &&
1294 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001295 HasCpp03IncompatibleFormat = true;
1296 Tok = &Tok->Children[0];
1297 }
1298 }
1299 if (Style.DerivePointerBinding) {
1300 if (CountBoundToType > CountBoundToVariable)
1301 Style.PointerBindsToType = true;
1302 else if (CountBoundToType < CountBoundToVariable)
1303 Style.PointerBindsToType = false;
1304 }
1305 if (Style.Standard == FormatStyle::LS_Auto) {
1306 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1307 : FormatStyle::LS_Cpp03;
1308 }
1309 }
1310
Manuel Klimekb95f5452013-02-08 17:38:27 +00001311 /// \brief Get the indent of \p Level from \p IndentForLevel.
1312 ///
1313 /// \p IndentForLevel must contain the indent for the level \c l
1314 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1315 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001316 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001317 if (IndentForLevel[Level] != -1)
1318 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001319 if (Level == 0)
1320 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001321 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001322 }
1323
1324 /// \brief Get the offset of the line relatively to the level.
1325 ///
1326 /// For example, 'public:' labels in classes are offset by 1 or 2
1327 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001328 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001329 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001330 return Style.AccessModifierOffset;
1331 return 0;
1332 }
1333
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001334 /// \brief Tries to merge lines into one.
1335 ///
1336 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1337 /// if possible; note that \c I will be incremented when lines are merged.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001338 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001339 std::vector<AnnotatedLine>::iterator &I,
1340 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001341 // We can never merge stuff if there are trailing line comments.
1342 if (I->Last->Type == TT_LineComment)
1343 return;
1344
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001345 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001346 // If we already exceed the column limit, we set 'Limit' to 0. The different
1347 // tryMerge..() functions can then decide whether to still do merging.
1348 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001349
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001350 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001351 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001352
Daniel Jasperabca58c2013-05-15 14:09:55 +00001353 if (I->Last->is(tok::l_brace)) {
Daniel Jasper25837aa2013-01-14 14:14:23 +00001354 tryMergeSimpleBlock(I, E, Limit);
1355 } else if (I->First.is(tok::kw_if)) {
1356 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001357 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1358 I->First.FormatTok.IsFirst)) {
1359 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001360 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001361 }
1362
Daniel Jasper39825ea2013-01-14 15:40:57 +00001363 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1364 std::vector<AnnotatedLine>::iterator E,
1365 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001366 if (Limit == 0)
1367 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001368 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001369 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1370 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001371 if (I + 2 != E && (I + 2)->InPPDirective &&
1372 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1373 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001374 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001375 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001376 join(Line, *(++I));
1377 }
1378
Daniel Jasper25837aa2013-01-14 14:14:23 +00001379 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1380 std::vector<AnnotatedLine>::iterator E,
1381 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001382 if (Limit == 0)
1383 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001384 if (!Style.AllowShortIfStatementsOnASingleLine)
1385 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001386 if ((I + 1)->InPPDirective != I->InPPDirective ||
1387 ((I + 1)->InPPDirective &&
1388 (I + 1)->First.FormatTok.HasUnescapedNewline))
1389 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001390 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001391 if (Line.Last->isNot(tok::r_paren))
1392 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001393 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001394 return;
1395 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1396 return;
1397 // Only inline simple if's (no nested if or else).
1398 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1399 return;
1400 join(Line, *(++I));
1401 }
1402
1403 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001404 std::vector<AnnotatedLine>::iterator E,
1405 unsigned Limit) {
Daniel Jasperabca58c2013-05-15 14:09:55 +00001406 // No merging if the brace already is on the next line.
1407 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
1408 return;
1409
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001410 // First, check that the current line allows merging. This is the case if
1411 // we're not in a control flow statement and the last token is an opening
1412 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001413 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001414 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1415 tok::kw_else, tok::kw_try, tok::kw_catch,
Daniel Jasperabca58c2013-05-15 14:09:55 +00001416 tok::kw_for, tok::kw_namespace,
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001417 // This gets rid of all ObjC @ keywords and methods.
1418 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001419 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001420
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001421 AnnotatedToken *Tok = &(I + 1)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001422 if (Tok->getNextNoneComment() == NULL && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001423 !Tok->MustBreakBefore) {
1424 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001425 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001426 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001427 join(Line, *(I + 1));
1428 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001429 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001430 // Check that we still have three lines and they fit into the limit.
1431 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1432 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001433 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001434
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001435 // Second, check that the next line does not contain any braces - if it
1436 // does, readability declines when putting it into a single line.
1437 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1438 return;
1439 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001440 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001441 return;
1442 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1443 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001444
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001445 // Last, check that the third line contains a single closing brace.
1446 Tok = &(I + 2)->First;
Daniel Jasperf9eb9b12013-05-16 10:17:39 +00001447 if (Tok->getNextNoneComment() != NULL || Tok->isNot(tok::r_brace) ||
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001448 Tok->MustBreakBefore)
1449 return;
1450
1451 join(Line, *(I + 1));
1452 join(Line, *(I + 2));
1453 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001454 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001455 }
1456
1457 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1458 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001459 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1460 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001461 }
1462
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001463 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001464 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001465 A.Last->Children.push_back(B.First);
1466 while (!A.Last->Children.empty()) {
1467 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001468 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001469 A.Last = &A.Last->Children[0];
1470 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001471 }
1472
Daniel Jasper97b89482013-03-13 07:49:51 +00001473 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001474 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1475 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1476 Ranges[i].getBegin()) &&
1477 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1478 Range.getBegin()))
1479 return true;
1480 }
1481 return false;
1482 }
1483
1484 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001485 const FormatToken *First = &TheLine.First.FormatTok;
1486 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercdd06622013-05-14 10:31:09 +00001487 CharSourceRange LineRange = CharSourceRange::getCharRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001488 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
Daniel Jaspercdd06622013-05-14 10:31:09 +00001489 Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001490 return touchesRanges(LineRange);
1491 }
1492
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001493 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1494 std::vector<AnnotatedLine>::iterator E) {
1495 for (; I != E; ++I) {
1496 if (I->First.FormatTok.HasUnescapedNewline)
1497 return false;
1498 if (touchesLine(*I))
1499 return true;
1500 }
1501 return false;
1502 }
1503
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001504 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1505 const FormatToken *First = &TheLine.First.FormatTok;
1506 CharSourceRange LineRange = CharSourceRange::getCharRange(
1507 First->WhiteSpaceStart,
1508 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1509 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001510 }
1511
1512 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001513 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001514 }
1515
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001516 /// \brief Add a new line and the required indent before the first Token
1517 /// of the \c UnwrappedLine if there was no structural parsing error.
1518 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001519 void formatFirstToken(const AnnotatedToken &RootToken,
1520 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001521 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001522 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001523
Daniel Jasperbbc84152013-01-29 11:27:30 +00001524 unsigned Newlines =
1525 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001526 if (Newlines == 0 && !Tok.IsFirst)
1527 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001528
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001529 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001530 // Insert extra new line before access specifiers.
1531 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1532 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1533 ++Newlines;
1534
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001535 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001536 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001537 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001538 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001539 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001540 }
1541
Daniel Jasperf7935112012-12-03 18:12:45 +00001542 FormatStyle Style;
1543 Lexer &Lex;
1544 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001545 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001546 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001547 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001548};
1549
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001550tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1551 SourceManager &SourceMgr,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +00001552 std::vector<CharSourceRange> Ranges) {
1553 Formatter formatter(Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001554 return formatter.format();
1555}
1556
Daniel Jasperec04c0d2013-05-16 10:40:07 +00001557tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
1558 std::vector<tooling::Range> Ranges,
1559 StringRef FileName) {
1560 FileManager Files((FileSystemOptions()));
1561 DiagnosticsEngine Diagnostics(
1562 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
1563 new DiagnosticOptions);
1564 SourceManager SourceMgr(Diagnostics, Files);
1565 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
1566 const clang::FileEntry *Entry =
1567 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
1568 SourceMgr.overrideFileContents(Entry, Buf);
1569 FileID ID =
1570 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
1571 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, getFormattingLangOpts());
1572 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
1573 std::vector<CharSourceRange> CharRanges;
1574 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1575 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
1576 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
1577 CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
1578 }
1579 return reformat(Style, Lex, SourceMgr, CharRanges);
1580}
1581
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001582LangOptions getFormattingLangOpts() {
1583 LangOptions LangOpts;
1584 LangOpts.CPlusPlus = 1;
1585 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001586 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001587 LangOpts.Bool = 1;
1588 LangOpts.ObjC1 = 1;
1589 LangOpts.ObjC2 = 1;
1590 return LangOpts;
1591}
1592
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001593} // namespace format
1594} // namespace clang