blob: f3ca9c371f1ecb1d67da1bae0a11ae74d0c38549 [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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Alexander Kornienkod6538332013-05-07 15:32:14 +000031#include "llvm/Support/YAMLTraits.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000032#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000033#include <string>
34
Alexander Kornienkod6538332013-05-07 15:32:14 +000035namespace llvm {
36namespace yaml {
37template <>
38struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
39 static void enumeration(IO &io,
40 clang::format::FormatStyle::LanguageStandard &value) {
41 io.enumCase(value, "C++03", clang::format::FormatStyle::LS_Cpp03);
42 io.enumCase(value, "C++11", clang::format::FormatStyle::LS_Cpp11);
43 io.enumCase(value, "Auto", clang::format::FormatStyle::LS_Auto);
44 }
45};
46
47template <> struct MappingTraits<clang::format::FormatStyle> {
48 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) {
Alexander Kornienko49149672013-05-10 11:56:10 +000049 if (IO.outputting()) {
50 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" };
51 ArrayRef<StringRef> Styles(StylesArray);
52 for (size_t i = 0, e = Styles.size(); i < e; ++i) {
53 StringRef StyleName(Styles[i]);
54 if (Style == clang::format::getPredefinedStyle(StyleName)) {
55 IO.mapOptional("# BasedOnStyle", StyleName);
56 break;
57 }
58 }
59 } else {
Alexander Kornienkod6538332013-05-07 15:32:14 +000060 StringRef BasedOnStyle;
61 IO.mapOptional("BasedOnStyle", BasedOnStyle);
Alexander Kornienkod6538332013-05-07 15:32:14 +000062 if (!BasedOnStyle.empty())
63 Style = clang::format::getPredefinedStyle(BasedOnStyle);
64 }
65
66 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
67 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
68 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
69 Style.AllowAllParametersOfDeclarationOnNextLine);
70 IO.mapOptional("AllowShortIfStatementsOnASingleLine",
71 Style.AllowShortIfStatementsOnASingleLine);
72 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
73 IO.mapOptional("ColumnLimit", Style.ColumnLimit);
74 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
75 Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
76 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
77 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
78 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
79 IO.mapOptional("ObjCSpaceBeforeProtocolList",
80 Style.ObjCSpaceBeforeProtocolList);
81 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
82 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
83 Style.PenaltyReturnTypeOnItsOwnLine);
84 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
85 IO.mapOptional("SpacesBeforeTrailingComments",
86 Style.SpacesBeforeTrailingComments);
87 IO.mapOptional("Standard", Style.Standard);
Manuel Klimek13b97d82013-05-13 08:42:42 +000088 IO.mapOptional("IndentWidth", Style.IndentWidth);
Alexander Kornienkod6538332013-05-07 15:32:14 +000089 }
90};
91}
92}
93
Daniel Jasperf7935112012-12-03 18:12:45 +000094namespace clang {
95namespace format {
96
Daniel Jasperf7935112012-12-03 18:12:45 +000097FormatStyle getLLVMStyle() {
98 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +000099 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000100 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000101 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000102 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000103 LLVMStyle.BinPackParameters = true;
104 LLVMStyle.ColumnLimit = 80;
105 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
106 LLVMStyle.DerivePointerBinding = false;
107 LLVMStyle.IndentCaseLabels = false;
108 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000109 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000110 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000111 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000112 LLVMStyle.PointerBindsToType = false;
113 LLVMStyle.SpacesBeforeTrailingComments = 1;
114 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000115 LLVMStyle.IndentWidth = 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000116 return LLVMStyle;
117}
118
119FormatStyle getGoogleStyle() {
120 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000121 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000122 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000123 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000124 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000125 GoogleStyle.BinPackParameters = true;
126 GoogleStyle.ColumnLimit = 80;
127 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
128 GoogleStyle.DerivePointerBinding = true;
129 GoogleStyle.IndentCaseLabels = true;
130 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000131 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000132 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000133 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000134 GoogleStyle.PointerBindsToType = true;
135 GoogleStyle.SpacesBeforeTrailingComments = 2;
136 GoogleStyle.Standard = FormatStyle::LS_Auto;
Manuel Klimek13b97d82013-05-13 08:42:42 +0000137 GoogleStyle.IndentWidth = 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000138 return GoogleStyle;
139}
140
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000141FormatStyle getChromiumStyle() {
142 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000143 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000144 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000145 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000146 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
147 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000148 return ChromiumStyle;
149}
150
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000151FormatStyle getMozillaStyle() {
152 FormatStyle MozillaStyle = getLLVMStyle();
153 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
154 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
155 MozillaStyle.DerivePointerBinding = true;
156 MozillaStyle.IndentCaseLabels = true;
157 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
158 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
159 MozillaStyle.PointerBindsToType = true;
160 return MozillaStyle;
161}
162
Alexander Kornienkod6538332013-05-07 15:32:14 +0000163FormatStyle getPredefinedStyle(StringRef Name) {
164 if (Name.equals_lower("llvm"))
165 return getLLVMStyle();
166 if (Name.equals_lower("chromium"))
167 return getChromiumStyle();
168 if (Name.equals_lower("mozilla"))
169 return getMozillaStyle();
170 if (Name.equals_lower("google"))
171 return getGoogleStyle();
172
173 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
174 return getGoogleStyle();
175}
176
177llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
178 llvm::yaml::Input Input(Text);
179 Input >> *Style;
180 return Input.error();
181}
182
183std::string configurationAsText(const FormatStyle &Style) {
184 std::string Text;
185 llvm::raw_string_ostream Stream(Text);
186 llvm::yaml::Output Output(Stream);
187 // We use the same mapping method for input and output, so we need a non-const
188 // reference here.
189 FormatStyle NonConstStyle = Style;
190 Output << NonConstStyle;
191 return Text;
192}
193
Daniel Jasperacc33662013-02-08 08:22:00 +0000194// Returns the length of everything up to the first possible line break after
195// the ), ], } or > matching \c Tok.
196static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
197 if (Tok.MatchingParen == NULL)
198 return 0;
199 AnnotatedToken *End = Tok.MatchingParen;
200 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
201 End = &End->Children[0];
202 }
203 return End->TotalLength - Tok.TotalLength + 1;
204}
205
Daniel Jasperf7935112012-12-03 18:12:45 +0000206class UnwrappedLineFormatter {
207public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000208 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000209 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000210 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000211 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000212 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000213 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000214 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000215
Manuel Klimek1abf7892013-01-04 23:34:14 +0000216 /// \brief Formats an \c UnwrappedLine.
217 ///
218 /// \returns The column after the last token in the last line of the
219 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000220 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000221 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000222 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000223 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000224 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000225 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000226 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000227 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000228 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000229 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000230 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000231 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000232
233 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000234 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000235
Daniel Jasper4b866272013-02-01 11:00:45 +0000236 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000237 unsigned ColumnLimit = Style.ColumnLimit;
238 if (NextLine && NextLine->InPPDirective &&
239 !NextLine->First.FormatTok.HasUnescapedNewline)
240 ColumnLimit = getColumnLimit();
241 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000242 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000243 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000244 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000245 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000246 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000247
Daniel Jasperacc33662013-02-08 08:22:00 +0000248 // If the ObjC method declaration does not fit on a line, we should format
249 // it with one arg per line.
250 if (Line.Type == LT_ObjCMethodDecl)
251 State.Stack.back().BreakBeforeParameter = true;
252
Daniel Jasper4b866272013-02-01 11:00:45 +0000253 // Find best solution in solution space.
254 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000255 }
256
257private:
Manuel Klimek24998102013-01-16 14:55:28 +0000258 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
259 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000260 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000261 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000262 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000263 }
264
Daniel Jasper337816e2013-01-11 10:22:12 +0000265 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000266 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000267 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000268 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
269 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000270 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000271 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
272 NestedNameSpecifierContinuation(0), CallContinuation(0),
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000273 VariablePos(0), ForFakeParenthesis(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000274
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 /// \brief The position to which a specific parenthesis level needs to be
276 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000277 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000278
Daniel Jaspere9de2602012-12-06 09:56:08 +0000279 /// \brief The position of the last space on each level.
280 ///
281 /// Used e.g. to break like:
282 /// functionCall(Parameter, otherCall(
283 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000284 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000285
Daniel Jaspere9de2602012-12-06 09:56:08 +0000286 /// \brief The position the first "<<" operator encountered on each level.
287 ///
288 /// Used to align "<<" operators. 0 if no such operator has been encountered
289 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000290 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000291
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000292 /// \brief Whether a newline needs to be inserted before the block's closing
293 /// brace.
294 ///
295 /// We only want to insert a newline before the closing brace if there also
296 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000297 bool BreakBeforeClosingBrace;
298
Daniel Jasperca6623b2013-01-28 12:45:14 +0000299 /// \brief The column of a \c ? in a conditional expression;
300 unsigned QuestionColumn;
301
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000302 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
303 /// lines, in this context.
304 bool AvoidBinPacking;
305
306 /// \brief Break after the next comma (or all the commas in this context if
307 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000308 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000309
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000310 /// \brief Line breaking in this context would break a formatting rule.
311 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000312
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000313 /// \brief The position of the colon in an ObjC method declaration/call.
314 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000315
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000316 /// \brief The start of the most recent function in a builder-type call.
317 unsigned StartOfFunctionCall;
318
Daniel Jasperc238c872013-04-02 14:33:13 +0000319 /// \brief If a nested name specifier was broken over multiple lines, this
320 /// contains the start column of the second line. Otherwise 0.
321 unsigned NestedNameSpecifierContinuation;
322
323 /// \brief If a call expression was broken over multiple lines, this
324 /// contains the start column of the second line. Otherwise 0.
325 unsigned CallContinuation;
326
Daniel Jaspera628c982013-04-03 13:36:17 +0000327 /// \brief The column of the first variable name in a variable declaration.
328 ///
329 /// Used to align further variables if necessary.
330 unsigned VariablePos;
331
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000332 /// \brief \c true if this \c ParenState was created for a fake parenthesis.
333 ///
334 /// Does not need to be considered for memoization / the comparison function
335 /// as otherwise identical states will have the same fake/non-fake
336 /// \c ParenStates.
337 bool ForFakeParenthesis;
338
Daniel Jasper337816e2013-01-11 10:22:12 +0000339 bool operator<(const ParenState &Other) const {
340 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000341 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000342 if (LastSpace != Other.LastSpace)
343 return LastSpace < Other.LastSpace;
344 if (FirstLessLess != Other.FirstLessLess)
345 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000346 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
347 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000348 if (QuestionColumn != Other.QuestionColumn)
349 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000350 if (AvoidBinPacking != Other.AvoidBinPacking)
351 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000352 if (BreakBeforeParameter != Other.BreakBeforeParameter)
353 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000354 if (NoLineBreak != Other.NoLineBreak)
355 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000356 if (ColonPos != Other.ColonPos)
357 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000358 if (StartOfFunctionCall != Other.StartOfFunctionCall)
359 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000360 if (CallContinuation != Other.CallContinuation)
361 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000362 if (VariablePos != Other.VariablePos)
363 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000364 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000365 }
366 };
367
368 /// \brief The current state when indenting a unwrapped line.
369 ///
370 /// As the indenting tries different combinations this is copied by value.
371 struct LineState {
372 /// \brief The number of used columns in the current line.
373 unsigned Column;
374
375 /// \brief The token that needs to be next formatted.
376 const AnnotatedToken *NextToken;
377
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000378 /// \brief \c true if this line contains a continued for-loop section.
379 bool LineContainsContinuedForLoopSection;
380
Daniel Jasper400adc62013-02-08 15:28:42 +0000381 /// \brief The level of nesting inside (), [], <> and {}.
382 unsigned ParenLevel;
383
Daniel Jasper40c36c52013-02-18 11:05:07 +0000384 /// \brief The \c ParenLevel at the start of this line.
385 unsigned StartOfLineLevel;
386
Manuel Klimek02f640a2013-02-20 15:25:48 +0000387 /// \brief The start column of the string literal, if we're in a string
388 /// literal sequence, 0 otherwise.
389 unsigned StartOfStringLiteral;
390
Daniel Jasper337816e2013-01-11 10:22:12 +0000391 /// \brief A stack keeping track of properties applying to parenthesis
392 /// levels.
393 std::vector<ParenState> Stack;
394
395 /// \brief Comparison operator to be able to used \c LineState in \c map.
396 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000397 if (NextToken != Other.NextToken)
398 return NextToken < Other.NextToken;
399 if (Column != Other.Column)
400 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000401 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000402 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000403 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000404 if (ParenLevel != Other.ParenLevel)
405 return ParenLevel < Other.ParenLevel;
406 if (StartOfLineLevel != Other.StartOfLineLevel)
407 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000408 if (StartOfStringLiteral != Other.StartOfStringLiteral)
409 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000410 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
412 };
413
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000414 /// \brief Appends the next token to \p State and updates information
415 /// necessary for indentation.
416 ///
417 /// Puts the token on the current line if \p Newline is \c true and adds a
418 /// line break and necessary indentation otherwise.
419 ///
420 /// If \p DryRun is \c false, also creates and stores the required
421 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000422 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000423 const AnnotatedToken &Current = *State.NextToken;
424 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jasper291f9362013-03-20 15:58:10 +0000426 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000427 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
428 State.NextToken->FormatTok.TokenLength;
429 if (State.NextToken->Children.empty())
430 State.NextToken = NULL;
431 else
432 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000433 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000434 }
435
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000436 // If we are continuing an expression, we want to indent an extra 4 spaces.
437 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000438 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000439 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000440 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000441 if (Current.is(tok::r_brace)) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000442 State.Column = Line.Level * Style.IndentWidth;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000443 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000444 State.StartOfStringLiteral != 0) {
445 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000446 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000447 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000448 State.Stack.back().FirstLessLess != 0) {
449 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000450 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000451 if (State.Stack.back().CallContinuation == 0) {
452 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000453 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000454 } else {
455 State.Column = State.Stack.back().CallContinuation;
456 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000457 } else if (Current.Type == TT_ConditionalExpr) {
458 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000459 } else if (Previous.is(tok::comma) &&
460 State.Stack.back().VariablePos != 0) {
461 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000462 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000463 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
464 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000465 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000466 } else if (Current.Type == TT_ObjCSelectorName) {
467 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
468 State.Column =
469 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
470 } else {
471 State.Column = State.Stack.back().Indent;
472 State.Stack.back().ColonPos =
473 State.Column + Current.FormatTok.TokenLength;
474 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000475 } else if (Current.Type == TT_StartOfName ||
476 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000477 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000478 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000479 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000480 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000481 // Ensure that we fall back to indenting 4 spaces instead of just
482 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000483 if (State.Column == FirstIndent)
484 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000485 }
486
Daniel Jasper54a86022013-02-15 11:07:25 +0000487 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000488 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000489 if ((Previous.isOneOf(tok::comma, tok::semi) &&
490 !State.Stack.back().AvoidBinPacking) ||
491 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000492 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000493
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000494 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000495 unsigned NewLines = 1;
496 if (Current.Type == TT_LineComment)
497 NewLines =
498 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
499 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000500 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000501 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000502 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000503 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000504 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000505 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000506 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000507
Daniel Jasper400adc62013-02-08 15:28:42 +0000508 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000509 if (Current.isOneOf(tok::arrow, tok::period))
510 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000511 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000512
513 // Any break on this level means that the parent level has been broken
514 // and we need to avoid bin packing there.
515 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
516 State.Stack[i].BreakBeforeParameter = true;
517 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000518 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
519 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000520 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000521 State.Stack.back().BreakBeforeParameter = true;
522
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000523 // If we break after {, we should also break before the corresponding }.
524 if (Previous.is(tok::l_brace))
525 State.Stack.back().BreakBeforeClosingBrace = true;
526
527 if (State.Stack.back().AvoidBinPacking) {
528 // If we are breaking after '(', '{', '<', this is not bin packing
529 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000530 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000531 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
532 Line.MustBeDeclaration))
533 State.Stack.back().BreakBeforeParameter = true;
534 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000535 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000536 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000537 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
538 State.Stack.back().VariablePos == 0) {
539 State.Stack.back().VariablePos = State.Column;
540 // Move over * and & if they are bound to the variable name.
541 const AnnotatedToken *Tok = &Previous;
542 while (Tok &&
543 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
544 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
545 if (Tok->SpacesRequiredBefore != 0)
546 break;
547 Tok = Tok->Parent;
548 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000549 if (Previous.PartOfMultiVariableDeclStmt)
550 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
551 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000552
Daniel Jaspereef30492013-02-11 12:36:37 +0000553 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554
Daniel Jasperf7935112012-12-03 18:12:45 +0000555 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000556 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000558 if (Current.Type == TT_ObjCSelectorName &&
559 State.Stack.back().ColonPos == 0) {
560 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000561 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000562 State.Stack.back().ColonPos =
563 State.Stack.back().Indent + Current.LongestObjCSelectorName;
564 else
565 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000566 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000567 }
568
Daniel Jasperc04baae2013-04-10 09:49:49 +0000569 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000570 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000571 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000572 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
573 State.Stack.back().AvoidBinPacking)
574 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000575
Daniel Jaspere9de2602012-12-06 09:56:08 +0000576 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000577 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000578 // Treat the condition inside an if as if it was a second function
579 // parameter, i.e. let nested calls have an indent of 4.
580 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000581 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000582 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000583 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000584 Previous.Type == TT_ConditionalExpr ||
585 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000586 getPrecedence(Previous) != prec::Assignment)
587 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000588 else if (Previous.Type == TT_InheritanceColon)
589 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000590 else if (Previous.opensScope() && !Current.FakeLParens.empty())
591 // If this function has multiple parameters or a binary expression
592 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000593 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000594 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000595
Manuel Klimek1998ea22013-02-20 10:15:13 +0000596 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000597 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000598
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599 /// \brief Mark the next token as consumed in \p State and modify its stacks
600 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000601 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000603 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000604
Daniel Jaspereead02b2013-02-14 08:42:54 +0000605 if (Current.Type == TT_InheritanceColon)
606 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000607 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
608 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000609 if (Current.is(tok::question))
610 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000611 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000612 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
613 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000614 Current.LastInChainOfCalls ? 0 : State.Column +
615 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000616 if (Current.Type == TT_CtorInitializerColon) {
Manuel Klimek13b97d82013-05-13 08:42:42 +0000617 // Indent 2 from the column, so:
618 // SomeClass::SomeClass()
619 // : First(...), ...
620 // Next(...)
621 // ^ line up here.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000622 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000623 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
624 State.Stack.back().AvoidBinPacking = true;
625 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000626 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000627
Daniel Jasper6bee6822013-04-08 20:33:42 +0000628 // If return returns a binary expression, align after it.
629 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
630 State.Stack.back().LastSpace = State.Column + 7;
631
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000632 // In ObjC method declaration we align on the ":" of parameters, but we need
633 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000634 if (Current.Type == TT_ObjCMethodSpecifier)
635 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000636
Daniel Jasper400adc62013-02-08 15:28:42 +0000637 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000638 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
639 // Don't add extra indentation for the first fake parenthesis after
640 // 'return', assignements or opening <({[. The indentation for these cases
641 // is special cased.
642 bool SkipFirstExtraIndent =
643 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000644 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000645 getPrecedence(*Previous) == prec::Assignment));
646 for (SmallVector<prec::Level, 4>::const_reverse_iterator
647 I = Current.FakeLParens.rbegin(),
648 E = Current.FakeLParens.rend();
649 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000650 ParenState NewParenState = State.Stack.back();
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000651 NewParenState.ForFakeParenthesis = true;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000652 NewParenState.Indent =
653 std::max(std::max(State.Column, NewParenState.Indent),
654 State.Stack.back().LastSpace);
655
656 // Always indent conditional expressions. Never indent expression where
657 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
658 // prec::Assignment) as those have different indentation rules. Indent
659 // other expression, unless the indentation needs to be skipped.
660 if (*I == prec::Conditional ||
661 (!SkipFirstExtraIndent && *I > prec::Assignment))
662 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000663 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000664 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000665 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000666 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000667 }
668
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000669 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000670 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000671 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000672 unsigned NewIndent;
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000673 unsigned LastSpace = State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000674 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000675 if (Current.is(tok::l_brace)) {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000676 NewIndent = Style.IndentWidth + LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000677 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000678 } else {
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000679 NewIndent =
680 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000681 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000682 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000683
684 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
685 // This parenthesis was the last token possibly making use of Indent and
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000686 // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000687 // better memoization results.
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000688 for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
689 State.Stack[i].Indent = 0;
690 State.Stack[i].LastSpace = 0;
691 if (!State.Stack[i].ForFakeParenthesis)
692 break;
693 }
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000694 }
695
Daniel Jaspercc3044c2013-05-13 09:19:24 +0000696 State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
697 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000698 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000699 }
700
Daniel Jasperacc33662013-02-08 08:22:00 +0000701 // If this '[' opens an ObjC call, determine whether all parameters fit into
702 // one line and put one per line if they don't.
703 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
704 Current.MatchingParen != NULL) {
705 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
706 State.Stack.back().BreakBeforeParameter = true;
707 }
708
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000709 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000710 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000711 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000712 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
713 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000714 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000715 --State.ParenLevel;
716 }
717
718 // Remove scopes created by fake parenthesis.
719 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000720 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000721 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000722 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000723 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000724
Manuel Klimek0c915712013-02-20 15:32:58 +0000725 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000726 State.StartOfStringLiteral = State.Column;
727 } else if (Current.isNot(tok::comment)) {
728 State.StartOfStringLiteral = 0;
729 }
730
Manuel Klimek1998ea22013-02-20 10:15:13 +0000731 State.Column += Current.FormatTok.TokenLength;
732
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000733 if (State.NextToken->Children.empty())
734 State.NextToken = NULL;
735 else
736 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000737
Manuel Klimek1998ea22013-02-20 10:15:13 +0000738 return breakProtrudingToken(Current, State, DryRun);
739 }
740
741 /// \brief If the current token sticks out over the end of the line, break
742 /// it if possible.
743 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
744 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000745 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000746 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000747 if (Current.is(tok::string_literal)) {
748 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000749 const char *LiteralData = SourceMgr.getCharacterData(
750 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000751 if (!LiteralData || *LiteralData != '"')
752 return 0;
753
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000754 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
755 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000756 } else if (Current.Type == TT_BlockComment) {
757 BreakableBlockComment *BBC =
758 new BreakableBlockComment(SourceMgr, Current, StartColumn);
759 if (!DryRun)
760 BBC->alignLines(Whitespaces);
761 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000762 } else if (Current.Type == TT_LineComment &&
763 (Current.Parent == NULL ||
764 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000765 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000766 } else {
767 return 0;
768 }
769
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000770 bool BreakInserted = false;
771 unsigned Penalty = 0;
772 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
773 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000774 unsigned TailOffset = 0;
775 unsigned RemainingLength =
776 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
777 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000778 BreakableToken::Split Split =
779 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
780 if (Split.first == StringRef::npos)
781 break;
782 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000783 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
784 LineIndex, TailOffset + Split.first + Split.second);
785 if (NewRemainingLength >= RemainingLength)
786 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000787 if (!DryRun) {
788 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
789 Whitespaces);
790 }
791 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000792 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000793 Penalty += Style.PenaltyExcessCharacter;
794 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000795 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000796 State.Column = RemainingLength;
797 if (!DryRun) {
798 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
799 }
800 }
801
802 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000803 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
804 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000805 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000806 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000807 return Penalty;
808 }
809
Daniel Jasper2df93312013-01-09 10:16:05 +0000810 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000811 // In preprocessor directives reserve two chars for trailing " \"
812 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000813 }
814
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000815 /// \brief An edge in the solution space from \c Previous->State to \c State,
816 /// inserting a newline dependent on the \c NewLine.
817 struct StateNode {
818 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000819 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000820 LineState State;
821 bool NewLine;
822 StateNode *Previous;
823 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000824
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000825 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
826 ///
827 /// In case of equal penalties, we want to prefer states that were inserted
828 /// first. During state generation we make sure that we insert states first
829 /// that break the line as late as possible.
830 typedef std::pair<unsigned, unsigned> OrderedPenalty;
831
832 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
833 /// \c State has the given \c OrderedPenalty.
834 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
835
836 /// \brief The BFS queue type.
837 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
838 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000839
840 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000842 /// This implements a variant of Dijkstra's algorithm on the graph that spans
843 /// the solution space (\c LineStates are the nodes). The algorithm tries to
844 /// find the shortest path (the one with lowest penalty) from \p InitialState
845 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000847 std::set<LineState> Seen;
848
Daniel Jasper4b866272013-02-01 11:00:45 +0000849 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000850 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
852 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
853 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000854
855 // While not empty, take first element and follow edges.
856 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000857 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000858 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000859 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000860 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000861 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000862 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000863 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000864
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000865 if (!Seen.insert(Node->State).second)
866 // State already examined with lower penalty.
867 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000868
Manuel Klimekaf491072013-02-13 10:54:19 +0000869 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
870 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000871 }
872
873 if (Queue.empty())
874 // We were unable to find a solution, do nothing.
875 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000876 return 0;
877
Daniel Jasper4b866272013-02-01 11:00:45 +0000878 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000879 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000880 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
881 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000882
Daniel Jasper4b866272013-02-01 11:00:45 +0000883 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000884 return Queue.top().second->State.Column;
885 }
886
887 void reconstructPath(LineState &State, StateNode *Current) {
888 // FIXME: This recursive implementation limits the possible number
889 // of tokens per line if compiled into a binary with small stack space.
890 // To become more independent of stack frame limitations we would need
891 // to also change the TokenAnnotator.
892 if (Current->Previous == NULL)
893 return;
894 reconstructPath(State, Current->Previous);
895 DEBUG({
896 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000897 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000898 << "Penalty for splitting before "
899 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
900 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000901 }
902 });
903 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000904 }
905
Manuel Klimekaf491072013-02-13 10:54:19 +0000906 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000907 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000908 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000909 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000910 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
911 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000912 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000913 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000914 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000915 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000916 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000917 Penalty += PreviousNode->State.NextToken->SplitPenalty;
918
919 StateNode *Node = new (Allocator.Allocate())
920 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000921 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000922 if (Node->State.Column > getColumnLimit()) {
923 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000924 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000925 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000926
927 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
928 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000929 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000930
Daniel Jasper4b866272013-02-01 11:00:45 +0000931 /// \brief Returns \c true, if a line break after \p State is allowed.
932 bool canBreak(const LineState &State) {
933 if (!State.NextToken->CanBreakBefore &&
934 !(State.NextToken->is(tok::r_brace) &&
935 State.Stack.back().BreakBeforeClosingBrace))
936 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000937 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000938 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000939
Daniel Jasper4b866272013-02-01 11:00:45 +0000940 /// \brief Returns \c true, if a line break after \p State is mandatory.
941 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000942 const AnnotatedToken &Current = *State.NextToken;
943 const AnnotatedToken &Previous = *Current.Parent;
944 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +0000945 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000946 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +0000947 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000948 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +0000949 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000950 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
951 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000952 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000953 !Current.isTrailingComment() &&
954 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000955 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000956
957 // If we need to break somewhere inside the LHS of a binary expression, we
958 // should also break after the operator.
959 if (Previous.Type == TT_BinaryOperator &&
960 !Previous.isOneOf(tok::lessless, tok::question) &&
961 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000962 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000963 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000964
965 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
966 // out whether it is the first parameter. Clean this up.
967 if (Current.Type == TT_ObjCSelectorName &&
968 Current.LongestObjCSelectorName == 0 &&
969 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +0000970 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000971 if ((Current.Type == TT_CtorInitializerColon ||
972 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +0000973 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000974
Daniel Jasper9b334242013-03-15 14:57:30 +0000975 // This prevents breaks like:
976 // ...
977 // SomeParameter, OtherParameter).DoSomething(
978 // ...
979 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +0000980 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +0000981 getRemainingLength(State) + State.Column > getColumnLimit() &&
982 State.ParenLevel < State.StartOfLineLevel)
983 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000984 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000985 }
986
Daniel Jasper9b334242013-03-15 14:57:30 +0000987 // Returns the total number of columns required for the remaining tokens.
988 unsigned getRemainingLength(const LineState &State) {
989 if (State.NextToken && State.NextToken->Parent)
990 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
991 return 0;
992 }
993
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 FormatStyle Style;
995 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000996 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000997 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000998 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000999 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001000
1001 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1002 QueueType Queue;
1003 // Increasing count of \c StateNode items we have created. This is used
1004 // to create a deterministic order independent of the container.
1005 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006};
1007
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001008class LexerBasedFormatTokenSource : public FormatTokenSource {
1009public:
1010 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001011 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001012 IdentTable(Lex.getLangOpts()) {
1013 Lex.SetKeepWhitespaceMode(true);
1014 }
1015
1016 virtual FormatToken getNextToken() {
1017 if (GreaterStashed) {
1018 FormatTok.NewlinesBefore = 0;
1019 FormatTok.WhiteSpaceStart =
1020 FormatTok.Tok.getLocation().getLocWithOffset(1);
1021 FormatTok.WhiteSpaceLength = 0;
1022 GreaterStashed = false;
1023 return FormatTok;
1024 }
1025
1026 FormatTok = FormatToken();
1027 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001028 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001029 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001030 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1031 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001032
1033 // Consume and record whitespace until we find a significant token.
1034 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001035 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001036 if (Newlines > 0)
1037 FormatTok.LastNewlineOffset =
1038 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001039 unsigned EscapedNewlines = Text.count("\\\n");
1040 FormatTok.NewlinesBefore += Newlines;
1041 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001042 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1043
1044 if (FormatTok.Tok.is(tok::eof))
1045 return FormatTok;
1046 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001047 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001048 }
Manuel Klimekef920692013-01-07 07:56:50 +00001049
1050 // Now FormatTok is the next non-whitespace token.
1051 FormatTok.TokenLength = Text.size();
1052
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001053 if (FormatTok.Tok.is(tok::comment)) {
1054 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1055 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1056 }
1057
Manuel Klimek1abf7892013-01-04 23:34:14 +00001058 // In case the token starts with escaped newlines, we want to
1059 // take them into account as whitespace - this pattern is quite frequent
1060 // in macro definitions.
1061 // FIXME: What do we want to do with other escaped spaces, and escaped
1062 // spaces or newlines in the middle of tokens?
1063 // FIXME: Add a more explicit test.
1064 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001065 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001066 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001067 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001068 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001069 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001070 }
1071
1072 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001073 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001074 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001075 FormatTok.Tok.setKind(Info.getTokenID());
1076 }
1077
1078 if (FormatTok.Tok.is(tok::greatergreater)) {
1079 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001080 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001081 GreaterStashed = true;
1082 }
1083
1084 return FormatTok;
1085 }
1086
Nico Weber29f9dea2013-02-11 15:32:15 +00001087 IdentifierTable &getIdentTable() { return IdentTable; }
1088
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001089private:
1090 FormatToken FormatTok;
1091 bool GreaterStashed;
1092 Lexer &Lex;
1093 SourceManager &SourceMgr;
1094 IdentifierTable IdentTable;
1095
1096 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001097 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001098 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1099 Tok.getLength());
1100 }
1101};
1102
Daniel Jasperf7935112012-12-03 18:12:45 +00001103class Formatter : public UnwrappedLineConsumer {
1104public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001105 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1106 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001107 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001108 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001109 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001110
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001111 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001112
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001113 tooling::Replacements format() {
1114 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1115 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001116 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001117 unsigned PreviousEndOfLineColumn = 0;
1118 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1119 Tokens.getIdentTable().get("in"));
1120 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1121 Annotator.annotate(AnnotatedLines[i]);
1122 }
1123 deriveLocalStyle();
1124 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1125 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1126 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001127
1128 // Adapt level to the next line if this is a comment.
1129 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001130 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001131 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1132 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1133 AnnotatedLines[i].First.Children.empty())
1134 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1135 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001136 NextNoneCommentLine =
1137 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1138 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001139 }
1140
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001141 std::vector<int> IndentForLevel;
1142 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001143 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001144 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001145 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1146 E = AnnotatedLines.end();
1147 I != E; ++I) {
1148 const AnnotatedLine &TheLine = *I;
1149 const FormatToken &FirstTok = TheLine.First.FormatTok;
1150 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001151
1152 // Check whether this line is part of a formatted preprocessor directive.
1153 if (FirstTok.HasUnescapedNewline)
1154 FormatPPDirective = false;
1155 if (!FormatPPDirective && TheLine.InPPDirective &&
1156 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1157 FormatPPDirective = true;
1158
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001159 while (IndentForLevel.size() <= TheLine.Level)
1160 IndentForLevel.push_back(-1);
1161 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001162 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001163 if (TheLine.First.is(tok::eof)) {
1164 if (PreviousLineWasTouched) {
1165 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1166 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001167 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001168 }
1169 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001170 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001171 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1172 unsigned Indent = LevelIndent;
1173 if (static_cast<int>(Indent) + Offset >= 0)
1174 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001175 if (FirstTok.WhiteSpaceStart.isValid() &&
1176 // Insert a break even if there is a structural error in case where
1177 // we break apart a line consisting of multiple unwrapped lines.
1178 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001179 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1180 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001181 } else {
1182 Indent = LevelIndent =
1183 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001184 }
1185 tryFitMultipleLinesInOne(Indent, I, E);
1186 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001187 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001188 PreviousEndOfLineColumn =
1189 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1190 IndentForLevel[TheLine.Level] = LevelIndent;
1191 PreviousLineWasTouched = true;
1192 } else {
1193 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1194 unsigned Indent =
1195 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1196 unsigned LevelIndent = Indent;
1197 if (static_cast<int>(LevelIndent) - Offset >= 0)
1198 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001199 if (TheLine.First.isNot(tok::comment))
1200 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001201
1202 // Remove trailing whitespace of the previous line if it was touched.
1203 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001204 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1205 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001206 }
1207 // If we did not reformat this unwrapped line, the column at the end of
1208 // the last token is unchanged - thus, we can calculate the end of the
1209 // last token.
1210 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1211 PreviousEndOfLineColumn =
1212 SourceMgr.getSpellingColumnNumber(LastLoc) +
1213 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1214 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001215 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001216 Whitespaces.addUntouchableComment(
1217 SourceMgr.getSpellingColumnNumber(
1218 TheLine.Last->FormatTok.Tok.getLocation()) -
1219 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001220 else
1221 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001222 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001223 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001224 }
1225 return Whitespaces.generateReplacements();
1226 }
1227
1228private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001229 void deriveLocalStyle() {
1230 unsigned CountBoundToVariable = 0;
1231 unsigned CountBoundToType = 0;
1232 bool HasCpp03IncompatibleFormat = false;
1233 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1234 if (AnnotatedLines[i].First.Children.empty())
1235 continue;
1236 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1237 while (!Tok->Children.empty()) {
1238 if (Tok->Type == TT_PointerOrReference) {
1239 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1240 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1241 if (SpacesBefore && !SpacesAfter)
1242 ++CountBoundToVariable;
1243 else if (!SpacesBefore && SpacesAfter)
1244 ++CountBoundToType;
1245 }
1246
Daniel Jasper400adc62013-02-08 15:28:42 +00001247 if (Tok->Type == TT_TemplateCloser &&
1248 Tok->Parent->Type == TT_TemplateCloser &&
1249 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001250 HasCpp03IncompatibleFormat = true;
1251 Tok = &Tok->Children[0];
1252 }
1253 }
1254 if (Style.DerivePointerBinding) {
1255 if (CountBoundToType > CountBoundToVariable)
1256 Style.PointerBindsToType = true;
1257 else if (CountBoundToType < CountBoundToVariable)
1258 Style.PointerBindsToType = false;
1259 }
1260 if (Style.Standard == FormatStyle::LS_Auto) {
1261 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1262 : FormatStyle::LS_Cpp03;
1263 }
1264 }
1265
Manuel Klimekb95f5452013-02-08 17:38:27 +00001266 /// \brief Get the indent of \p Level from \p IndentForLevel.
1267 ///
1268 /// \p IndentForLevel must contain the indent for the level \c l
1269 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1270 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001271 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001272 if (IndentForLevel[Level] != -1)
1273 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001274 if (Level == 0)
1275 return 0;
Manuel Klimek13b97d82013-05-13 08:42:42 +00001276 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001277 }
1278
1279 /// \brief Get the offset of the line relatively to the level.
1280 ///
1281 /// For example, 'public:' labels in classes are offset by 1 or 2
1282 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001283 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001284 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001285 return Style.AccessModifierOffset;
1286 return 0;
1287 }
1288
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001289 /// \brief Tries to merge lines into one.
1290 ///
1291 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1292 /// if possible; note that \c I will be incremented when lines are merged.
1293 ///
1294 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001295 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001296 std::vector<AnnotatedLine>::iterator &I,
1297 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001298 // We can never merge stuff if there are trailing line comments.
1299 if (I->Last->Type == TT_LineComment)
1300 return;
1301
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001302 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001303 // If we already exceed the column limit, we set 'Limit' to 0. The different
1304 // tryMerge..() functions can then decide whether to still do merging.
1305 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001306
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001307 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001308 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001309
Daniel Jasper25837aa2013-01-14 14:14:23 +00001310 if (I->Last->is(tok::l_brace)) {
1311 tryMergeSimpleBlock(I, E, Limit);
1312 } else if (I->First.is(tok::kw_if)) {
1313 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001314 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1315 I->First.FormatTok.IsFirst)) {
1316 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001317 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001318 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001319 }
1320
Daniel Jasper39825ea2013-01-14 15:40:57 +00001321 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1322 std::vector<AnnotatedLine>::iterator E,
1323 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001324 if (Limit == 0)
1325 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001326 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001327 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1328 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001329 if (I + 2 != E && (I + 2)->InPPDirective &&
1330 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1331 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001332 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001333 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001334 join(Line, *(++I));
1335 }
1336
Daniel Jasper25837aa2013-01-14 14:14:23 +00001337 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1338 std::vector<AnnotatedLine>::iterator E,
1339 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001340 if (Limit == 0)
1341 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001342 if (!Style.AllowShortIfStatementsOnASingleLine)
1343 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001344 if ((I + 1)->InPPDirective != I->InPPDirective ||
1345 ((I + 1)->InPPDirective &&
1346 (I + 1)->First.FormatTok.HasUnescapedNewline))
1347 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001348 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001349 if (Line.Last->isNot(tok::r_paren))
1350 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001351 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001352 return;
1353 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1354 return;
1355 // Only inline simple if's (no nested if or else).
1356 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1357 return;
1358 join(Line, *(++I));
1359 }
1360
1361 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001362 std::vector<AnnotatedLine>::iterator E,
1363 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001364 // First, check that the current line allows merging. This is the case if
1365 // we're not in a control flow statement and the last token is an opening
1366 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001367 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001368 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1369 tok::kw_else, tok::kw_try, tok::kw_catch,
1370 tok::kw_for,
1371 // This gets rid of all ObjC @ keywords and methods.
1372 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001373 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001374
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001375 AnnotatedToken *Tok = &(I + 1)->First;
1376 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001377 !Tok->MustBreakBefore) {
1378 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001379 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001380 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001381 join(Line, *(I + 1));
1382 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001383 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001384 // Check that we still have three lines and they fit into the limit.
1385 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1386 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001387 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001388
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001389 // Second, check that the next line does not contain any braces - if it
1390 // does, readability declines when putting it into a single line.
1391 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1392 return;
1393 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001394 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001395 return;
1396 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1397 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001398
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001399 // Last, check that the third line contains a single closing brace.
1400 Tok = &(I + 2)->First;
1401 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1402 Tok->MustBreakBefore)
1403 return;
1404
1405 join(Line, *(I + 1));
1406 join(Line, *(I + 2));
1407 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001408 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001409 }
1410
1411 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1412 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001413 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1414 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001415 }
1416
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001417 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001418 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001419 A.Last->Children.push_back(B.First);
1420 while (!A.Last->Children.empty()) {
1421 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001422 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001423 A.Last = &A.Last->Children[0];
1424 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001425 }
1426
Daniel Jasper97b89482013-03-13 07:49:51 +00001427 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001428 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1429 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1430 Ranges[i].getBegin()) &&
1431 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1432 Range.getBegin()))
1433 return true;
1434 }
1435 return false;
1436 }
1437
1438 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001439 const FormatToken *First = &TheLine.First.FormatTok;
1440 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001441 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001442 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1443 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001444 return touchesRanges(LineRange);
1445 }
1446
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001447 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1448 std::vector<AnnotatedLine>::iterator E) {
1449 for (; I != E; ++I) {
1450 if (I->First.FormatTok.HasUnescapedNewline)
1451 return false;
1452 if (touchesLine(*I))
1453 return true;
1454 }
1455 return false;
1456 }
1457
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001458 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1459 const FormatToken *First = &TheLine.First.FormatTok;
1460 CharSourceRange LineRange = CharSourceRange::getCharRange(
1461 First->WhiteSpaceStart,
1462 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1463 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001464 }
1465
1466 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001467 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001468 }
1469
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001470 /// \brief Add a new line and the required indent before the first Token
1471 /// of the \c UnwrappedLine if there was no structural parsing error.
1472 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001473 void formatFirstToken(const AnnotatedToken &RootToken,
1474 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001475 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001476 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001477
Daniel Jasperbbc84152013-01-29 11:27:30 +00001478 unsigned Newlines =
1479 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001480 if (Newlines == 0 && !Tok.IsFirst)
1481 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001482
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001483 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001484 // Insert extra new line before access specifiers.
1485 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1486 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1487 ++Newlines;
1488
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001489 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001490 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001491 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001492 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001493 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001494 }
1495
Alexander Kornienko116ba682013-01-14 11:34:14 +00001496 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001497 FormatStyle Style;
1498 Lexer &Lex;
1499 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001500 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001501 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001502 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001503};
1504
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001505tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1506 SourceManager &SourceMgr,
1507 std::vector<CharSourceRange> Ranges,
1508 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001509 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001510 OwningPtr<DiagnosticConsumer> DiagPrinter;
1511 if (DiagClient == 0) {
1512 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1513 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1514 DiagClient = DiagPrinter.get();
1515 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001516 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001517 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001518 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001519 Diagnostics.setSourceManager(&SourceMgr);
1520 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001521 return formatter.format();
1522}
1523
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001524LangOptions getFormattingLangOpts() {
1525 LangOptions LangOpts;
1526 LangOpts.CPlusPlus = 1;
1527 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001528 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001529 LangOpts.Bool = 1;
1530 LangOpts.ObjC1 = 1;
1531 LangOpts.ObjC2 = 1;
1532 return LangOpts;
1533}
1534
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001535} // namespace format
1536} // namespace clang