blob: 9a320f94bd13f61acaa7b4ad273bff535fe562cd [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);
88 }
89};
90}
91}
92
Daniel Jasperf7935112012-12-03 18:12:45 +000093namespace clang {
94namespace format {
95
Daniel Jasperf7935112012-12-03 18:12:45 +000096FormatStyle getLLVMStyle() {
97 FormatStyle LLVMStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +000098 LLVMStyle.AccessModifierOffset = -2;
Alexander Kornienkoc8602662013-05-06 14:11:27 +000099 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000100 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000101 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000102 LLVMStyle.BinPackParameters = true;
103 LLVMStyle.ColumnLimit = 80;
104 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
105 LLVMStyle.DerivePointerBinding = false;
106 LLVMStyle.IndentCaseLabels = false;
107 LLVMStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000108 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000109 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000110 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000111 LLVMStyle.PointerBindsToType = false;
112 LLVMStyle.SpacesBeforeTrailingComments = 1;
113 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Daniel Jasperf7935112012-12-03 18:12:45 +0000114 return LLVMStyle;
115}
116
117FormatStyle getGoogleStyle() {
118 FormatStyle GoogleStyle;
Daniel Jasperf7935112012-12-03 18:12:45 +0000119 GoogleStyle.AccessModifierOffset = -1;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000120 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000121 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000122 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000123 GoogleStyle.BinPackParameters = true;
124 GoogleStyle.ColumnLimit = 80;
125 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
126 GoogleStyle.DerivePointerBinding = true;
127 GoogleStyle.IndentCaseLabels = true;
128 GoogleStyle.MaxEmptyLinesToKeep = 1;
Nico Webera6087752013-01-10 20:12:55 +0000129 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000130 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +0000131 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000132 GoogleStyle.PointerBindsToType = true;
133 GoogleStyle.SpacesBeforeTrailingComments = 2;
134 GoogleStyle.Standard = FormatStyle::LS_Auto;
Daniel Jasperf7935112012-12-03 18:12:45 +0000135 return GoogleStyle;
136}
137
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000138FormatStyle getChromiumStyle() {
139 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000140 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +0000141 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000142 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000143 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
144 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000145 return ChromiumStyle;
146}
147
Alexander Kornienkoc8602662013-05-06 14:11:27 +0000148FormatStyle getMozillaStyle() {
149 FormatStyle MozillaStyle = getLLVMStyle();
150 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
151 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
152 MozillaStyle.DerivePointerBinding = true;
153 MozillaStyle.IndentCaseLabels = true;
154 MozillaStyle.ObjCSpaceBeforeProtocolList = false;
155 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
156 MozillaStyle.PointerBindsToType = true;
157 return MozillaStyle;
158}
159
Alexander Kornienkod6538332013-05-07 15:32:14 +0000160FormatStyle getPredefinedStyle(StringRef Name) {
161 if (Name.equals_lower("llvm"))
162 return getLLVMStyle();
163 if (Name.equals_lower("chromium"))
164 return getChromiumStyle();
165 if (Name.equals_lower("mozilla"))
166 return getMozillaStyle();
167 if (Name.equals_lower("google"))
168 return getGoogleStyle();
169
170 llvm::errs() << "Unknown style " << Name << ", using Google style.\n";
171 return getGoogleStyle();
172}
173
174llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
175 llvm::yaml::Input Input(Text);
176 Input >> *Style;
177 return Input.error();
178}
179
180std::string configurationAsText(const FormatStyle &Style) {
181 std::string Text;
182 llvm::raw_string_ostream Stream(Text);
183 llvm::yaml::Output Output(Stream);
184 // We use the same mapping method for input and output, so we need a non-const
185 // reference here.
186 FormatStyle NonConstStyle = Style;
187 Output << NonConstStyle;
188 return Text;
189}
190
Daniel Jasperacc33662013-02-08 08:22:00 +0000191// Returns the length of everything up to the first possible line break after
192// the ), ], } or > matching \c Tok.
193static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
194 if (Tok.MatchingParen == NULL)
195 return 0;
196 AnnotatedToken *End = Tok.MatchingParen;
197 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
198 End = &End->Children[0];
199 }
200 return End->TotalLength - Tok.TotalLength + 1;
201}
202
Daniel Jasperf7935112012-12-03 18:12:45 +0000203class UnwrappedLineFormatter {
204public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000205 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000206 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000207 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000208 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000209 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000210 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000211 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000212
Manuel Klimek1abf7892013-01-04 23:34:14 +0000213 /// \brief Formats an \c UnwrappedLine.
214 ///
215 /// \returns The column after the last token in the last line of the
216 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000217 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000218 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000219 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000220 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000221 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000222 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000223 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000224 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000225 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000226 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000227 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000228 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000229
230 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000231 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000232
Daniel Jasper4b866272013-02-01 11:00:45 +0000233 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000234 unsigned ColumnLimit = Style.ColumnLimit;
235 if (NextLine && NextLine->InPPDirective &&
236 !NextLine->First.FormatTok.HasUnescapedNewline)
237 ColumnLimit = getColumnLimit();
238 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000239 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000240 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000241 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000242 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000243 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000244
Daniel Jasperacc33662013-02-08 08:22:00 +0000245 // If the ObjC method declaration does not fit on a line, we should format
246 // it with one arg per line.
247 if (Line.Type == LT_ObjCMethodDecl)
248 State.Stack.back().BreakBeforeParameter = true;
249
Daniel Jasper4b866272013-02-01 11:00:45 +0000250 // Find best solution in solution space.
251 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000252 }
253
254private:
Manuel Klimek24998102013-01-16 14:55:28 +0000255 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
256 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Alexander Kornienko49149672013-05-10 11:56:10 +0000257 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000258 Tok.getLength());
Alexander Kornienko49149672013-05-10 11:56:10 +0000259 llvm::dbgs();
Manuel Klimek24998102013-01-16 14:55:28 +0000260 }
261
Daniel Jasper337816e2013-01-11 10:22:12 +0000262 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000263 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000264 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000265 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
266 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000267 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000268 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
269 NestedNameSpecifierContinuation(0), CallContinuation(0),
270 VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000271
Daniel Jasperf7935112012-12-03 18:12:45 +0000272 /// \brief The position to which a specific parenthesis level needs to be
273 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000274 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000275
Daniel Jaspere9de2602012-12-06 09:56:08 +0000276 /// \brief The position of the last space on each level.
277 ///
278 /// Used e.g. to break like:
279 /// functionCall(Parameter, otherCall(
280 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000281 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000282
Daniel Jaspere9de2602012-12-06 09:56:08 +0000283 /// \brief The position the first "<<" operator encountered on each level.
284 ///
285 /// Used to align "<<" operators. 0 if no such operator has been encountered
286 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000287 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000288
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000289 /// \brief Whether a newline needs to be inserted before the block's closing
290 /// brace.
291 ///
292 /// We only want to insert a newline before the closing brace if there also
293 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000294 bool BreakBeforeClosingBrace;
295
Daniel Jasperca6623b2013-01-28 12:45:14 +0000296 /// \brief The column of a \c ? in a conditional expression;
297 unsigned QuestionColumn;
298
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000299 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
300 /// lines, in this context.
301 bool AvoidBinPacking;
302
303 /// \brief Break after the next comma (or all the commas in this context if
304 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000305 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000306
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000307 /// \brief Line breaking in this context would break a formatting rule.
308 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000309
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000310 /// \brief The position of the colon in an ObjC method declaration/call.
311 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000312
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000313 /// \brief The start of the most recent function in a builder-type call.
314 unsigned StartOfFunctionCall;
315
Daniel Jasperc238c872013-04-02 14:33:13 +0000316 /// \brief If a nested name specifier was broken over multiple lines, this
317 /// contains the start column of the second line. Otherwise 0.
318 unsigned NestedNameSpecifierContinuation;
319
320 /// \brief If a call expression was broken over multiple lines, this
321 /// contains the start column of the second line. Otherwise 0.
322 unsigned CallContinuation;
323
Daniel Jaspera628c982013-04-03 13:36:17 +0000324 /// \brief The column of the first variable name in a variable declaration.
325 ///
326 /// Used to align further variables if necessary.
327 unsigned VariablePos;
328
Daniel Jasper337816e2013-01-11 10:22:12 +0000329 bool operator<(const ParenState &Other) const {
330 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000331 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000332 if (LastSpace != Other.LastSpace)
333 return LastSpace < Other.LastSpace;
334 if (FirstLessLess != Other.FirstLessLess)
335 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000336 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
337 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000338 if (QuestionColumn != Other.QuestionColumn)
339 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000340 if (AvoidBinPacking != Other.AvoidBinPacking)
341 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000342 if (BreakBeforeParameter != Other.BreakBeforeParameter)
343 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000344 if (NoLineBreak != Other.NoLineBreak)
345 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000346 if (ColonPos != Other.ColonPos)
347 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000348 if (StartOfFunctionCall != Other.StartOfFunctionCall)
349 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000350 if (CallContinuation != Other.CallContinuation)
351 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000352 if (VariablePos != Other.VariablePos)
353 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000354 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000355 }
356 };
357
358 /// \brief The current state when indenting a unwrapped line.
359 ///
360 /// As the indenting tries different combinations this is copied by value.
361 struct LineState {
362 /// \brief The number of used columns in the current line.
363 unsigned Column;
364
365 /// \brief The token that needs to be next formatted.
366 const AnnotatedToken *NextToken;
367
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000368 /// \brief \c true if this line contains a continued for-loop section.
369 bool LineContainsContinuedForLoopSection;
370
Daniel Jasper400adc62013-02-08 15:28:42 +0000371 /// \brief The level of nesting inside (), [], <> and {}.
372 unsigned ParenLevel;
373
Daniel Jasper40c36c52013-02-18 11:05:07 +0000374 /// \brief The \c ParenLevel at the start of this line.
375 unsigned StartOfLineLevel;
376
Manuel Klimek02f640a2013-02-20 15:25:48 +0000377 /// \brief The start column of the string literal, if we're in a string
378 /// literal sequence, 0 otherwise.
379 unsigned StartOfStringLiteral;
380
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 /// \brief A stack keeping track of properties applying to parenthesis
382 /// levels.
383 std::vector<ParenState> Stack;
384
385 /// \brief Comparison operator to be able to used \c LineState in \c map.
386 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000387 if (NextToken != Other.NextToken)
388 return NextToken < Other.NextToken;
389 if (Column != Other.Column)
390 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000391 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000392 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000393 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000394 if (ParenLevel != Other.ParenLevel)
395 return ParenLevel < Other.ParenLevel;
396 if (StartOfLineLevel != Other.StartOfLineLevel)
397 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000398 if (StartOfStringLiteral != Other.StartOfStringLiteral)
399 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000400 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000401 }
402 };
403
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000404 /// \brief Appends the next token to \p State and updates information
405 /// necessary for indentation.
406 ///
407 /// Puts the token on the current line if \p Newline is \c true and adds a
408 /// line break and necessary indentation otherwise.
409 ///
410 /// If \p DryRun is \c false, also creates and stores the required
411 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000412 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000413 const AnnotatedToken &Current = *State.NextToken;
414 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000415
Daniel Jasper291f9362013-03-20 15:58:10 +0000416 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000417 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
418 State.NextToken->FormatTok.TokenLength;
419 if (State.NextToken->Children.empty())
420 State.NextToken = NULL;
421 else
422 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000423 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000424 }
425
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000426 // If we are continuing an expression, we want to indent an extra 4 spaces.
427 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000428 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000429 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000430 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000431 if (Current.is(tok::r_brace)) {
432 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000433 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000434 State.StartOfStringLiteral != 0) {
435 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000436 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000437 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000438 State.Stack.back().FirstLessLess != 0) {
439 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000440 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000441 if (State.Stack.back().CallContinuation == 0) {
442 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000443 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000444 } else {
445 State.Column = State.Stack.back().CallContinuation;
446 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000447 } else if (Current.Type == TT_ConditionalExpr) {
448 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000449 } else if (Previous.is(tok::comma) &&
450 State.Stack.back().VariablePos != 0) {
451 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000452 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000453 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
454 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000455 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000456 } else if (Current.Type == TT_ObjCSelectorName) {
457 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
458 State.Column =
459 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
460 } else {
461 State.Column = State.Stack.back().Indent;
462 State.Stack.back().ColonPos =
463 State.Column + Current.FormatTok.TokenLength;
464 }
Daniel Jasper0f0234e2013-05-08 10:00:18 +0000465 } else if (Current.Type == TT_StartOfName ||
466 Previous.isOneOf(tok::coloncolon, tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000467 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000468 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000469 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000470 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000471 // Ensure that we fall back to indenting 4 spaces instead of just
472 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000473 if (State.Column == FirstIndent)
474 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000475 }
476
Daniel Jasper54a86022013-02-15 11:07:25 +0000477 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000478 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000479 if ((Previous.isOneOf(tok::comma, tok::semi) &&
480 !State.Stack.back().AvoidBinPacking) ||
481 Previous.Type == TT_BinaryOperator)
Daniel Jasperacc33662013-02-08 08:22:00 +0000482 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000483
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000484 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000485 unsigned NewLines = 1;
486 if (Current.Type == TT_LineComment)
487 NewLines =
488 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
489 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000490 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000491 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000492 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000493 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000494 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000495 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000496 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000497
Daniel Jasper400adc62013-02-08 15:28:42 +0000498 State.Stack.back().LastSpace = State.Column;
Daniel Jasper66e4f832013-05-10 13:37:16 +0000499 if (Current.isOneOf(tok::arrow, tok::period))
500 State.Stack.back().LastSpace += Current.FormatTok.TokenLength;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000501 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000502
503 // Any break on this level means that the parent level has been broken
504 // and we need to avoid bin packing there.
505 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
506 State.Stack[i].BreakBeforeParameter = true;
507 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000508 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
509 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000510 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000511 State.Stack.back().BreakBeforeParameter = true;
512
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000513 // If we break after {, we should also break before the corresponding }.
514 if (Previous.is(tok::l_brace))
515 State.Stack.back().BreakBeforeClosingBrace = true;
516
517 if (State.Stack.back().AvoidBinPacking) {
518 // If we are breaking after '(', '{', '<', this is not bin packing
519 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000520 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000521 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
522 Line.MustBeDeclaration))
523 State.Stack.back().BreakBeforeParameter = true;
524 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000526 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000527 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
528 State.Stack.back().VariablePos == 0) {
529 State.Stack.back().VariablePos = State.Column;
530 // Move over * and & if they are bound to the variable name.
531 const AnnotatedToken *Tok = &Previous;
532 while (Tok &&
533 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
534 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
535 if (Tok->SpacesRequiredBefore != 0)
536 break;
537 Tok = Tok->Parent;
538 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000539 if (Previous.PartOfMultiVariableDeclStmt)
540 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
541 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000542
Daniel Jaspereef30492013-02-11 12:36:37 +0000543 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000544
Daniel Jasperf7935112012-12-03 18:12:45 +0000545 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000546 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000547
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000548 if (Current.Type == TT_ObjCSelectorName &&
549 State.Stack.back().ColonPos == 0) {
550 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000551 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000552 State.Stack.back().ColonPos =
553 State.Stack.back().Indent + Current.LongestObjCSelectorName;
554 else
555 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000556 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000557 }
558
Daniel Jasperc04baae2013-04-10 09:49:49 +0000559 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000560 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000561 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000562 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
563 State.Stack.back().AvoidBinPacking)
564 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000565
Daniel Jaspere9de2602012-12-06 09:56:08 +0000566 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000567 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000568 // Treat the condition inside an if as if it was a second function
569 // parameter, i.e. let nested calls have an indent of 4.
570 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000571 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000572 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000573 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000574 Previous.Type == TT_ConditionalExpr ||
575 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000576 getPrecedence(Previous) != prec::Assignment)
577 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000578 else if (Previous.Type == TT_InheritanceColon)
579 State.Stack.back().Indent = State.Column;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000580 else if (Previous.opensScope() && !Current.FakeLParens.empty())
581 // If this function has multiple parameters or a binary expression
582 // parameter, indent nested calls from the start of the first parameter.
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000583 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000585
Manuel Klimek1998ea22013-02-20 10:15:13 +0000586 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000587 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000588
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589 /// \brief Mark the next token as consumed in \p State and modify its stacks
590 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000591 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000592 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000593 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000594
Daniel Jaspereead02b2013-02-14 08:42:54 +0000595 if (Current.Type == TT_InheritanceColon)
596 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000597 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
598 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000599 if (Current.is(tok::question))
600 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000601 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000602 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
603 State.Stack.back().StartOfFunctionCall =
Daniel Jasper66e4f832013-05-10 13:37:16 +0000604 Current.LastInChainOfCalls ? 0 : State.Column +
605 Current.FormatTok.TokenLength;
Daniel Jasper37905f72013-02-21 15:00:29 +0000606 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000607 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000608 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
609 State.Stack.back().AvoidBinPacking = true;
610 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000611 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000612
Daniel Jasper6bee6822013-04-08 20:33:42 +0000613 // If return returns a binary expression, align after it.
614 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
615 State.Stack.back().LastSpace = State.Column + 7;
616
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000617 // In ObjC method declaration we align on the ":" of parameters, but we need
618 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000619 if (Current.Type == TT_ObjCMethodSpecifier)
620 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000621
Daniel Jasper400adc62013-02-08 15:28:42 +0000622 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000623 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
624 // Don't add extra indentation for the first fake parenthesis after
625 // 'return', assignements or opening <({[. The indentation for these cases
626 // is special cased.
627 bool SkipFirstExtraIndent =
628 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000629 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000630 getPrecedence(*Previous) == prec::Assignment));
631 for (SmallVector<prec::Level, 4>::const_reverse_iterator
632 I = Current.FakeLParens.rbegin(),
633 E = Current.FakeLParens.rend();
634 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000635 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000636 NewParenState.Indent =
637 std::max(std::max(State.Column, NewParenState.Indent),
638 State.Stack.back().LastSpace);
639
640 // Always indent conditional expressions. Never indent expression where
641 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
642 // prec::Assignment) as those have different indentation rules. Indent
643 // other expression, unless the indentation needs to be skipped.
644 if (*I == prec::Conditional ||
645 (!SkipFirstExtraIndent && *I > prec::Assignment))
646 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000647 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000648 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000649 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000650 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000651 }
652
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000653 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000655 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000656 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000657 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000658 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000659 NewIndent = 2 + State.Stack.back().LastSpace;
660 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000661 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000662 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
663 State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000664 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000665 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000666 State.Stack.push_back(
667 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000668 State.Stack.back().NoLineBreak));
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000669
670 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
671 // This parenthesis was the last token possibly making use of Indent and
672 // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
673 // better memoization results.
674 State.Stack[State.Stack.size() - 2].Indent = 0;
675 State.Stack[State.Stack.size() - 2].LastSpace = 0;
676 }
677
Daniel Jasper400adc62013-02-08 15:28:42 +0000678 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000679 }
680
Daniel Jasperacc33662013-02-08 08:22:00 +0000681 // If this '[' opens an ObjC call, determine whether all parameters fit into
682 // one line and put one per line if they don't.
683 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
684 Current.MatchingParen != NULL) {
685 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
686 State.Stack.back().BreakBeforeParameter = true;
687 }
688
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000689 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000690 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000691 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000692 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
693 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000694 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000695 --State.ParenLevel;
696 }
697
698 // Remove scopes created by fake parenthesis.
699 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000700 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000701 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000702 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000703 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000704
Manuel Klimek0c915712013-02-20 15:32:58 +0000705 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000706 State.StartOfStringLiteral = State.Column;
707 } else if (Current.isNot(tok::comment)) {
708 State.StartOfStringLiteral = 0;
709 }
710
Manuel Klimek1998ea22013-02-20 10:15:13 +0000711 State.Column += Current.FormatTok.TokenLength;
712
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000713 if (State.NextToken->Children.empty())
714 State.NextToken = NULL;
715 else
716 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000717
Manuel Klimek1998ea22013-02-20 10:15:13 +0000718 return breakProtrudingToken(Current, State, DryRun);
719 }
720
721 /// \brief If the current token sticks out over the end of the line, break
722 /// it if possible.
723 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
724 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000725 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000726 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000727 if (Current.is(tok::string_literal)) {
728 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000729 const char *LiteralData = SourceMgr.getCharacterData(
730 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000731 if (!LiteralData || *LiteralData != '"')
732 return 0;
733
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000734 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
735 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000736 } else if (Current.Type == TT_BlockComment) {
737 BreakableBlockComment *BBC =
738 new BreakableBlockComment(SourceMgr, Current, StartColumn);
739 if (!DryRun)
740 BBC->alignLines(Whitespaces);
741 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000742 } else if (Current.Type == TT_LineComment &&
743 (Current.Parent == NULL ||
744 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000745 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000746 } else {
747 return 0;
748 }
749
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000750 bool BreakInserted = false;
751 unsigned Penalty = 0;
752 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
753 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000754 unsigned TailOffset = 0;
755 unsigned RemainingLength =
756 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
757 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000758 BreakableToken::Split Split =
759 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
760 if (Split.first == StringRef::npos)
761 break;
762 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000763 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
764 LineIndex, TailOffset + Split.first + Split.second);
765 if (NewRemainingLength >= RemainingLength)
766 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000767 if (!DryRun) {
768 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
769 Whitespaces);
770 }
771 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000772 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000773 Penalty += Style.PenaltyExcessCharacter;
774 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000775 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000776 State.Column = RemainingLength;
777 if (!DryRun) {
778 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
779 }
780 }
781
782 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000783 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
784 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000785 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000786 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000787 return Penalty;
788 }
789
Daniel Jasper2df93312013-01-09 10:16:05 +0000790 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000791 // In preprocessor directives reserve two chars for trailing " \"
792 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000793 }
794
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000795 /// \brief An edge in the solution space from \c Previous->State to \c State,
796 /// inserting a newline dependent on the \c NewLine.
797 struct StateNode {
798 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000799 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000800 LineState State;
801 bool NewLine;
802 StateNode *Previous;
803 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000804
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000805 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
806 ///
807 /// In case of equal penalties, we want to prefer states that were inserted
808 /// first. During state generation we make sure that we insert states first
809 /// that break the line as late as possible.
810 typedef std::pair<unsigned, unsigned> OrderedPenalty;
811
812 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
813 /// \c State has the given \c OrderedPenalty.
814 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
815
816 /// \brief The BFS queue type.
817 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
818 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000819
820 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000821 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000822 /// This implements a variant of Dijkstra's algorithm on the graph that spans
823 /// the solution space (\c LineStates are the nodes). The algorithm tries to
824 /// find the shortest path (the one with lowest penalty) from \p InitialState
825 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000826 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000827 std::set<LineState> Seen;
828
Daniel Jasper4b866272013-02-01 11:00:45 +0000829 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000830 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000831 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
832 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
833 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000834
835 // While not empty, take first element and follow edges.
836 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000837 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000838 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000839 if (Node->State.NextToken == NULL) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000840 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000841 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000842 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000843 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000844
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000845 if (!Seen.insert(Node->State).second)
846 // State already examined with lower penalty.
847 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000848
Manuel Klimekaf491072013-02-13 10:54:19 +0000849 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
850 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000851 }
852
853 if (Queue.empty())
854 // We were unable to find a solution, do nothing.
855 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000856 return 0;
857
Daniel Jasper4b866272013-02-01 11:00:45 +0000858 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000859 reconstructPath(InitialState, Queue.top().second);
Alexander Kornienko49149672013-05-10 11:56:10 +0000860 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
861 DEBUG(llvm::dbgs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000862
Daniel Jasper4b866272013-02-01 11:00:45 +0000863 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000864 return Queue.top().second->State.Column;
865 }
866
867 void reconstructPath(LineState &State, StateNode *Current) {
868 // FIXME: This recursive implementation limits the possible number
869 // of tokens per line if compiled into a binary with small stack space.
870 // To become more independent of stack frame limitations we would need
871 // to also change the TokenAnnotator.
872 if (Current->Previous == NULL)
873 return;
874 reconstructPath(State, Current->Previous);
875 DEBUG({
876 if (Current->NewLine) {
Alexander Kornienko49149672013-05-10 11:56:10 +0000877 llvm::dbgs()
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000878 << "Penalty for splitting before "
879 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
880 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000881 }
882 });
883 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000884 }
885
Manuel Klimekaf491072013-02-13 10:54:19 +0000886 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000887 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000888 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000889 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000890 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
891 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000892 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000893 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000894 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000895 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000896 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000897 Penalty += PreviousNode->State.NextToken->SplitPenalty;
898
899 StateNode *Node = new (Allocator.Allocate())
900 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000901 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000902 if (Node->State.Column > getColumnLimit()) {
903 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000904 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000905 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906
907 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
908 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000909 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000910
Daniel Jasper4b866272013-02-01 11:00:45 +0000911 /// \brief Returns \c true, if a line break after \p State is allowed.
912 bool canBreak(const LineState &State) {
913 if (!State.NextToken->CanBreakBefore &&
914 !(State.NextToken->is(tok::r_brace) &&
915 State.Stack.back().BreakBeforeClosingBrace))
916 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000917 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000918 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000919
Daniel Jasper4b866272013-02-01 11:00:45 +0000920 /// \brief Returns \c true, if a line break after \p State is mandatory.
921 bool mustBreak(const LineState &State) {
Daniel Jasperd69fc772013-05-08 14:12:04 +0000922 const AnnotatedToken &Current = *State.NextToken;
923 const AnnotatedToken &Previous = *Current.Parent;
924 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon)
Daniel Jasper4b866272013-02-01 11:00:45 +0000925 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000926 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace)
Daniel Jasper4b866272013-02-01 11:00:45 +0000927 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000928 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
Daniel Jasper4b866272013-02-01 11:00:45 +0000929 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000930 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) ||
931 Current.Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000932 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperd69fc772013-05-08 14:12:04 +0000933 !Current.isTrailingComment() &&
934 !Current.isOneOf(tok::r_paren, tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000935 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000936
937 // If we need to break somewhere inside the LHS of a binary expression, we
938 // should also break after the operator.
939 if (Previous.Type == TT_BinaryOperator &&
940 !Previous.isOneOf(tok::lessless, tok::question) &&
941 getPrecedence(Previous) != prec::Assignment &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000942 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000943 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000944
945 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
946 // out whether it is the first parameter. Clean this up.
947 if (Current.Type == TT_ObjCSelectorName &&
948 Current.LongestObjCSelectorName == 0 &&
949 State.Stack.back().BreakBeforeParameter)
Daniel Jasper4b866272013-02-01 11:00:45 +0000950 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000951 if ((Current.Type == TT_CtorInitializerColon ||
952 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0)))
Daniel Jasper40aacf42013-03-14 13:45:21 +0000953 return true;
Daniel Jasperd69fc772013-05-08 14:12:04 +0000954
Daniel Jasper9b334242013-03-15 14:57:30 +0000955 // This prevents breaks like:
956 // ...
957 // SomeParameter, OtherParameter).DoSomething(
958 // ...
959 // As they hide "DoSomething" and generally bad for readability.
Daniel Jasperd69fc772013-05-08 14:12:04 +0000960 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper9b334242013-03-15 14:57:30 +0000961 getRemainingLength(State) + State.Column > getColumnLimit() &&
962 State.ParenLevel < State.StartOfLineLevel)
963 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000964 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 }
966
Daniel Jasper9b334242013-03-15 14:57:30 +0000967 // Returns the total number of columns required for the remaining tokens.
968 unsigned getRemainingLength(const LineState &State) {
969 if (State.NextToken && State.NextToken->Parent)
970 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
971 return 0;
972 }
973
Daniel Jasperf7935112012-12-03 18:12:45 +0000974 FormatStyle Style;
975 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000976 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000977 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000978 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000979 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000980
981 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
982 QueueType Queue;
983 // Increasing count of \c StateNode items we have created. This is used
984 // to create a deterministic order independent of the container.
985 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000986};
987
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000988class LexerBasedFormatTokenSource : public FormatTokenSource {
989public:
990 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000991 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000992 IdentTable(Lex.getLangOpts()) {
993 Lex.SetKeepWhitespaceMode(true);
994 }
995
996 virtual FormatToken getNextToken() {
997 if (GreaterStashed) {
998 FormatTok.NewlinesBefore = 0;
999 FormatTok.WhiteSpaceStart =
1000 FormatTok.Tok.getLocation().getLocWithOffset(1);
1001 FormatTok.WhiteSpaceLength = 0;
1002 GreaterStashed = false;
1003 return FormatTok;
1004 }
1005
1006 FormatTok = FormatToken();
1007 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001008 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001009 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001010 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1011 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001012
1013 // Consume and record whitespace until we find a significant token.
1014 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001015 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001016 if (Newlines > 0)
1017 FormatTok.LastNewlineOffset =
1018 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001019 unsigned EscapedNewlines = Text.count("\\\n");
1020 FormatTok.NewlinesBefore += Newlines;
1021 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001022 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1023
1024 if (FormatTok.Tok.is(tok::eof))
1025 return FormatTok;
1026 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001027 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001028 }
Manuel Klimekef920692013-01-07 07:56:50 +00001029
1030 // Now FormatTok is the next non-whitespace token.
1031 FormatTok.TokenLength = Text.size();
1032
Alexander Kornienko9e90b622013-04-17 17:34:05 +00001033 if (FormatTok.Tok.is(tok::comment)) {
1034 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
1035 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
1036 }
1037
Manuel Klimek1abf7892013-01-04 23:34:14 +00001038 // In case the token starts with escaped newlines, we want to
1039 // take them into account as whitespace - this pattern is quite frequent
1040 // in macro definitions.
1041 // FIXME: What do we want to do with other escaped spaces, and escaped
1042 // spaces or newlines in the middle of tokens?
1043 // FIXME: Add a more explicit test.
1044 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001045 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001046 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001047 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001048 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001049 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001050 }
1051
1052 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001053 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001054 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001055 FormatTok.Tok.setKind(Info.getTokenID());
1056 }
1057
1058 if (FormatTok.Tok.is(tok::greatergreater)) {
1059 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001060 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001061 GreaterStashed = true;
1062 }
1063
1064 return FormatTok;
1065 }
1066
Nico Weber29f9dea2013-02-11 15:32:15 +00001067 IdentifierTable &getIdentTable() { return IdentTable; }
1068
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001069private:
1070 FormatToken FormatTok;
1071 bool GreaterStashed;
1072 Lexer &Lex;
1073 SourceManager &SourceMgr;
1074 IdentifierTable IdentTable;
1075
1076 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001077 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001078 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1079 Tok.getLength());
1080 }
1081};
1082
Daniel Jasperf7935112012-12-03 18:12:45 +00001083class Formatter : public UnwrappedLineConsumer {
1084public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001085 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1086 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001087 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001088 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001089 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001090
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001091 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001092
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001093 tooling::Replacements format() {
1094 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1095 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001096 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001097 unsigned PreviousEndOfLineColumn = 0;
1098 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1099 Tokens.getIdentTable().get("in"));
1100 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1101 Annotator.annotate(AnnotatedLines[i]);
1102 }
1103 deriveLocalStyle();
1104 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1105 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1106 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001107
1108 // Adapt level to the next line if this is a comment.
1109 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001110 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001111 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1112 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1113 AnnotatedLines[i].First.Children.empty())
1114 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1115 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001116 NextNoneCommentLine =
1117 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1118 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001119 }
1120
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001121 std::vector<int> IndentForLevel;
1122 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001123 const AnnotatedToken *PreviousLineLastToken = 0;
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001124 bool FormatPPDirective = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001125 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1126 E = AnnotatedLines.end();
1127 I != E; ++I) {
1128 const AnnotatedLine &TheLine = *I;
1129 const FormatToken &FirstTok = TheLine.First.FormatTok;
1130 int Offset = getIndentOffset(TheLine.First);
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001131
1132 // Check whether this line is part of a formatted preprocessor directive.
1133 if (FirstTok.HasUnescapedNewline)
1134 FormatPPDirective = false;
1135 if (!FormatPPDirective && TheLine.InPPDirective &&
1136 (touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
1137 FormatPPDirective = true;
1138
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001139 while (IndentForLevel.size() <= TheLine.Level)
1140 IndentForLevel.push_back(-1);
1141 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001142 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001143 if (TheLine.First.is(tok::eof)) {
1144 if (PreviousLineWasTouched) {
1145 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1146 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001147 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001148 }
1149 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001150 (WasMoved || FormatPPDirective || touchesLine(TheLine))) {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001151 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1152 unsigned Indent = LevelIndent;
1153 if (static_cast<int>(Indent) + Offset >= 0)
1154 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001155 if (FirstTok.WhiteSpaceStart.isValid() &&
1156 // Insert a break even if there is a structural error in case where
1157 // we break apart a line consisting of multiple unwrapped lines.
1158 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001159 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1160 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001161 } else {
1162 Indent = LevelIndent =
1163 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001164 }
1165 tryFitMultipleLinesInOne(Indent, I, E);
1166 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001167 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001168 PreviousEndOfLineColumn =
1169 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1170 IndentForLevel[TheLine.Level] = LevelIndent;
1171 PreviousLineWasTouched = true;
1172 } else {
1173 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1174 unsigned Indent =
1175 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1176 unsigned LevelIndent = Indent;
1177 if (static_cast<int>(LevelIndent) - Offset >= 0)
1178 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001179 if (TheLine.First.isNot(tok::comment))
1180 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001181
1182 // Remove trailing whitespace of the previous line if it was touched.
1183 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001184 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1185 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001186 }
1187 // If we did not reformat this unwrapped line, the column at the end of
1188 // the last token is unchanged - thus, we can calculate the end of the
1189 // last token.
1190 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1191 PreviousEndOfLineColumn =
1192 SourceMgr.getSpellingColumnNumber(LastLoc) +
1193 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1194 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001195 if (TheLine.Last->is(tok::comment))
Daniel Jasperd69fc772013-05-08 14:12:04 +00001196 Whitespaces.addUntouchableComment(
1197 SourceMgr.getSpellingColumnNumber(
1198 TheLine.Last->FormatTok.Tok.getLocation()) -
1199 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001200 else
1201 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001202 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001203 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001204 }
1205 return Whitespaces.generateReplacements();
1206 }
1207
1208private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001209 void deriveLocalStyle() {
1210 unsigned CountBoundToVariable = 0;
1211 unsigned CountBoundToType = 0;
1212 bool HasCpp03IncompatibleFormat = false;
1213 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1214 if (AnnotatedLines[i].First.Children.empty())
1215 continue;
1216 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1217 while (!Tok->Children.empty()) {
1218 if (Tok->Type == TT_PointerOrReference) {
1219 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1220 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1221 if (SpacesBefore && !SpacesAfter)
1222 ++CountBoundToVariable;
1223 else if (!SpacesBefore && SpacesAfter)
1224 ++CountBoundToType;
1225 }
1226
Daniel Jasper400adc62013-02-08 15:28:42 +00001227 if (Tok->Type == TT_TemplateCloser &&
1228 Tok->Parent->Type == TT_TemplateCloser &&
1229 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001230 HasCpp03IncompatibleFormat = true;
1231 Tok = &Tok->Children[0];
1232 }
1233 }
1234 if (Style.DerivePointerBinding) {
1235 if (CountBoundToType > CountBoundToVariable)
1236 Style.PointerBindsToType = true;
1237 else if (CountBoundToType < CountBoundToVariable)
1238 Style.PointerBindsToType = false;
1239 }
1240 if (Style.Standard == FormatStyle::LS_Auto) {
1241 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1242 : FormatStyle::LS_Cpp03;
1243 }
1244 }
1245
Manuel Klimekb95f5452013-02-08 17:38:27 +00001246 /// \brief Get the indent of \p Level from \p IndentForLevel.
1247 ///
1248 /// \p IndentForLevel must contain the indent for the level \c l
1249 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1250 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001251 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001252 if (IndentForLevel[Level] != -1)
1253 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001254 if (Level == 0)
1255 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001256 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001257 }
1258
1259 /// \brief Get the offset of the line relatively to the level.
1260 ///
1261 /// For example, 'public:' labels in classes are offset by 1 or 2
1262 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001263 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001264 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001265 return Style.AccessModifierOffset;
1266 return 0;
1267 }
1268
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001269 /// \brief Tries to merge lines into one.
1270 ///
1271 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1272 /// if possible; note that \c I will be incremented when lines are merged.
1273 ///
1274 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001275 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001276 std::vector<AnnotatedLine>::iterator &I,
1277 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001278 // We can never merge stuff if there are trailing line comments.
1279 if (I->Last->Type == TT_LineComment)
1280 return;
1281
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001282 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001283 // If we already exceed the column limit, we set 'Limit' to 0. The different
1284 // tryMerge..() functions can then decide whether to still do merging.
1285 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001286
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001287 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001288 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001289
Daniel Jasper25837aa2013-01-14 14:14:23 +00001290 if (I->Last->is(tok::l_brace)) {
1291 tryMergeSimpleBlock(I, E, Limit);
1292 } else if (I->First.is(tok::kw_if)) {
1293 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001294 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1295 I->First.FormatTok.IsFirst)) {
1296 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001297 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001298 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001299 }
1300
Daniel Jasper39825ea2013-01-14 15:40:57 +00001301 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1302 std::vector<AnnotatedLine>::iterator E,
1303 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001304 if (Limit == 0)
1305 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001306 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001307 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1308 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001309 if (I + 2 != E && (I + 2)->InPPDirective &&
1310 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1311 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001312 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001313 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001314 join(Line, *(++I));
1315 }
1316
Daniel Jasper25837aa2013-01-14 14:14:23 +00001317 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1318 std::vector<AnnotatedLine>::iterator E,
1319 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001320 if (Limit == 0)
1321 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001322 if (!Style.AllowShortIfStatementsOnASingleLine)
1323 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001324 if ((I + 1)->InPPDirective != I->InPPDirective ||
1325 ((I + 1)->InPPDirective &&
1326 (I + 1)->First.FormatTok.HasUnescapedNewline))
1327 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001328 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001329 if (Line.Last->isNot(tok::r_paren))
1330 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001331 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001332 return;
1333 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1334 return;
1335 // Only inline simple if's (no nested if or else).
1336 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1337 return;
1338 join(Line, *(++I));
1339 }
1340
1341 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001342 std::vector<AnnotatedLine>::iterator E,
1343 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001344 // First, check that the current line allows merging. This is the case if
1345 // we're not in a control flow statement and the last token is an opening
1346 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001347 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001348 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1349 tok::kw_else, tok::kw_try, tok::kw_catch,
1350 tok::kw_for,
1351 // This gets rid of all ObjC @ keywords and methods.
1352 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001353 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001354
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001355 AnnotatedToken *Tok = &(I + 1)->First;
1356 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001357 !Tok->MustBreakBefore) {
1358 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001359 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001360 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001361 join(Line, *(I + 1));
1362 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001363 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001364 // Check that we still have three lines and they fit into the limit.
1365 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1366 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001367 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001368
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001369 // Second, check that the next line does not contain any braces - if it
1370 // does, readability declines when putting it into a single line.
1371 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1372 return;
1373 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001374 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001375 return;
1376 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1377 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001378
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001379 // Last, check that the third line contains a single closing brace.
1380 Tok = &(I + 2)->First;
1381 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1382 Tok->MustBreakBefore)
1383 return;
1384
1385 join(Line, *(I + 1));
1386 join(Line, *(I + 2));
1387 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001388 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001389 }
1390
1391 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1392 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001393 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1394 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001395 }
1396
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001397 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001398 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001399 A.Last->Children.push_back(B.First);
1400 while (!A.Last->Children.empty()) {
1401 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001402 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001403 A.Last = &A.Last->Children[0];
1404 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001405 }
1406
Daniel Jasper97b89482013-03-13 07:49:51 +00001407 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001408 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1409 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1410 Ranges[i].getBegin()) &&
1411 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1412 Range.getBegin()))
1413 return true;
1414 }
1415 return false;
1416 }
1417
1418 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001419 const FormatToken *First = &TheLine.First.FormatTok;
1420 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001421 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001422 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1423 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001424 return touchesRanges(LineRange);
1425 }
1426
Daniel Jasper1cb530f2013-05-10 13:00:49 +00001427 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I,
1428 std::vector<AnnotatedLine>::iterator E) {
1429 for (; I != E; ++I) {
1430 if (I->First.FormatTok.HasUnescapedNewline)
1431 return false;
1432 if (touchesLine(*I))
1433 return true;
1434 }
1435 return false;
1436 }
1437
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001438 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1439 const FormatToken *First = &TheLine.First.FormatTok;
1440 CharSourceRange LineRange = CharSourceRange::getCharRange(
1441 First->WhiteSpaceStart,
1442 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1443 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001444 }
1445
1446 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001447 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001448 }
1449
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001450 /// \brief Add a new line and the required indent before the first Token
1451 /// of the \c UnwrappedLine if there was no structural parsing error.
1452 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001453 void formatFirstToken(const AnnotatedToken &RootToken,
1454 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001455 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001456 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001457
Daniel Jasperbbc84152013-01-29 11:27:30 +00001458 unsigned Newlines =
1459 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001460 if (Newlines == 0 && !Tok.IsFirst)
1461 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001462
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001463 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001464 // Insert extra new line before access specifiers.
1465 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1466 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1467 ++Newlines;
1468
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001469 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001470 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001471 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001472 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001473 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001474 }
1475
Alexander Kornienko116ba682013-01-14 11:34:14 +00001476 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001477 FormatStyle Style;
1478 Lexer &Lex;
1479 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001480 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001481 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001482 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001483};
1484
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001485tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1486 SourceManager &SourceMgr,
1487 std::vector<CharSourceRange> Ranges,
1488 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001489 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001490 OwningPtr<DiagnosticConsumer> DiagPrinter;
1491 if (DiagClient == 0) {
1492 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1493 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1494 DiagClient = DiagPrinter.get();
1495 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001496 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001497 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001498 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001499 Diagnostics.setSourceManager(&SourceMgr);
1500 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001501 return formatter.format();
1502}
1503
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001504LangOptions getFormattingLangOpts() {
1505 LangOptions LangOpts;
1506 LangOpts.CPlusPlus = 1;
1507 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001508 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001509 LangOpts.Bool = 1;
1510 LangOpts.ObjC1 = 1;
1511 LangOpts.ObjC2 = 1;
1512 return LangOpts;
1513}
1514
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001515} // namespace format
1516} // namespace clang