blob: 932f86785988dd93804777bb9bb16235a4fc81ce [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
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimek24998102013-01-16 14:55:28 +000029// Uncomment to get debug output from tests:
30// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000047 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000048 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000049 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000050 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000051 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000065 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +000067 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000068 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000069 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000070 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000071 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper94f0e132013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperacc33662013-02-08 08:22:00 +000088// Returns the length of everything up to the first possible line break after
89// the ), ], } or > matching \c Tok.
90static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
91 if (Tok.MatchingParen == NULL)
92 return 0;
93 AnnotatedToken *End = Tok.MatchingParen;
94 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
95 End = &End->Children[0];
96 }
97 return End->TotalLength - Tok.TotalLength + 1;
98}
99
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000100/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000101///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000102/// This includes special handling for certain constructs, e.g. the alignment of
103/// trailing line comments.
104class WhitespaceManager {
105public:
106 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
107
108 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
109 /// each \c AnnotatedToken.
110 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
111 unsigned Spaces, unsigned WhitespaceStartColumn,
112 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000113 // 2+ newlines mean an empty line separating logic scopes.
114 if (NewLines >= 2)
115 alignComments();
116
117 // Align line comments if they are trailing or if they continue other
118 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000119 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 if (Style.ColumnLimit >=
121 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
122 Comments.push_back(StoredComment());
123 Comments.back().Tok = Tok.FormatTok;
124 Comments.back().Spaces = Spaces;
125 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000126 if (NewLines == 0)
127 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
128 else
129 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000130 Comments.back().MaxColumn =
131 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000132 return;
133 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000134 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000135
136 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000137 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000138 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000139 storeReplacement(Tok.FormatTok,
140 std::string(NewLines, '\n') + std::string(Spaces, ' '));
141 }
142
143 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
144 /// backslashes to escape newlines inside a preprocessor directive.
145 ///
146 /// This function and \c replaceWhitespace have the same behavior if
147 /// \c Newlines == 0.
148 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
149 unsigned Spaces, unsigned WhitespaceStartColumn,
150 const FormatStyle &Style) {
151 std::string NewLineText;
152 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000153 unsigned Offset =
154 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000155 for (unsigned i = 0; i < NewLines; ++i) {
156 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
157 NewLineText += "\\\n";
158 Offset = 0;
159 }
160 }
161 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
162 }
163
164 /// \brief Returns all the \c Replacements created during formatting.
165 const tooling::Replacements &generateReplacements() {
166 alignComments();
167 return Replaces;
168 }
169
170private:
171 /// \brief Structure to store a comment for later layout and alignment.
172 struct StoredComment {
173 FormatToken Tok;
174 unsigned MinColumn;
175 unsigned MaxColumn;
176 unsigned NewLines;
177 unsigned Spaces;
178 };
179 SmallVector<StoredComment, 16> Comments;
180 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
181
182 /// \brief Try to align all stashed comments.
183 void alignComments() {
184 unsigned MinColumn = 0;
185 unsigned MaxColumn = UINT_MAX;
186 comment_iterator Start = Comments.begin();
187 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
188 ++I) {
189 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
190 alignComments(Start, I, MinColumn);
191 MinColumn = I->MinColumn;
192 MaxColumn = I->MaxColumn;
193 Start = I;
194 } else {
195 MinColumn = std::max(MinColumn, I->MinColumn);
196 MaxColumn = std::min(MaxColumn, I->MaxColumn);
197 }
198 }
199 alignComments(Start, Comments.end(), MinColumn);
200 Comments.clear();
201 }
202
203 /// \brief Put all the comments between \p I and \p E into \p Column.
204 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
205 while (I != E) {
206 unsigned Spaces = I->Spaces + Column - I->MinColumn;
207 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
208 std::string(Spaces, ' '));
209 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000210 }
211 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212
213 /// \brief Stores \p Text as the replacement for the whitespace in front of
214 /// \p Tok.
215 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000216 // Don't create a replacement, if it does not change anything.
217 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
218 Tok.WhiteSpaceLength) == Text)
219 return;
220
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000221 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
222 Tok.WhiteSpaceLength, Text));
223 }
224
225 SourceManager &SourceMgr;
226 tooling::Replacements Replaces;
227};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000228
Daniel Jasperf7935112012-12-03 18:12:45 +0000229class UnwrappedLineFormatter {
230public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000231 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000232 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000233 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000234 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000235 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000236 FirstIndent(FirstIndent), RootToken(RootToken),
237 Whitespaces(Whitespaces) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000238 }
239
Manuel Klimek1abf7892013-01-04 23:34:14 +0000240 /// \brief Formats an \c UnwrappedLine.
241 ///
242 /// \returns The column after the last token in the last line of the
243 /// \c UnwrappedLine.
244 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000245 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000246 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000247 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000248 State.NextToken = &RootToken;
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000249 State.Stack.push_back(
250 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
251 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000252 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000253 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000254
Manuel Klimek24998102013-01-16 14:55:28 +0000255 DEBUG({
256 DebugTokenState(*State.NextToken);
257 });
258
Daniel Jaspere9de2602012-12-06 09:56:08 +0000259 // The first token has already been indented and thus consumed.
260 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000261
Daniel Jasper4b866272013-02-01 11:00:45 +0000262 // If everything fits on a single line, just put it there.
263 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
264 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000265 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000266 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000267 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000268 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000269
Daniel Jasperacc33662013-02-08 08:22:00 +0000270 // If the ObjC method declaration does not fit on a line, we should format
271 // it with one arg per line.
272 if (Line.Type == LT_ObjCMethodDecl)
273 State.Stack.back().BreakBeforeParameter = true;
274
Daniel Jasper4b866272013-02-01 11:00:45 +0000275 // Find best solution in solution space.
276 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000277 }
278
279private:
Manuel Klimek24998102013-01-16 14:55:28 +0000280 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
281 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000282 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
283 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000284 llvm::errs();
285 }
286
Daniel Jasper337816e2013-01-11 10:22:12 +0000287 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000288 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
289 bool HasMultiParameterLine)
Daniel Jaspera836b902013-01-23 16:58:21 +0000290 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000291 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000292 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000293 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000294 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000295
Daniel Jasperf7935112012-12-03 18:12:45 +0000296 /// \brief The position to which a specific parenthesis level needs to be
297 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000298 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000299
Daniel Jaspere9de2602012-12-06 09:56:08 +0000300 /// \brief The position of the last space on each level.
301 ///
302 /// Used e.g. to break like:
303 /// functionCall(Parameter, otherCall(
304 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000305 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000306
Daniel Jaspera836b902013-01-23 16:58:21 +0000307 /// \brief This is the column of the first token after an assignment.
308 unsigned AssignmentColumn;
309
Daniel Jaspere9de2602012-12-06 09:56:08 +0000310 /// \brief The position the first "<<" operator encountered on each level.
311 ///
312 /// Used to align "<<" operators. 0 if no such operator has been encountered
313 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000314 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000315
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000316 /// \brief Whether a newline needs to be inserted before the block's closing
317 /// brace.
318 ///
319 /// We only want to insert a newline before the closing brace if there also
320 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000321 bool BreakBeforeClosingBrace;
322
Daniel Jasperca6623b2013-01-28 12:45:14 +0000323 /// \brief The column of a \c ? in a conditional expression;
324 unsigned QuestionColumn;
325
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000326 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
327 /// lines, in this context.
328 bool AvoidBinPacking;
329
330 /// \brief Break after the next comma (or all the commas in this context if
331 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000332 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000333
334 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000335 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000336
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000337 /// \brief The position of the colon in an ObjC method declaration/call.
338 unsigned ColonPos;
339
Daniel Jasper337816e2013-01-11 10:22:12 +0000340 bool operator<(const ParenState &Other) const {
341 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000342 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000343 if (LastSpace != Other.LastSpace)
344 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000345 if (AssignmentColumn != Other.AssignmentColumn)
346 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000347 if (FirstLessLess != Other.FirstLessLess)
348 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000349 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
350 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000351 if (QuestionColumn != Other.QuestionColumn)
352 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000353 if (AvoidBinPacking != Other.AvoidBinPacking)
354 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000355 if (BreakBeforeParameter != Other.BreakBeforeParameter)
356 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000357 if (HasMultiParameterLine != Other.HasMultiParameterLine)
358 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000359 if (ColonPos != Other.ColonPos)
360 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000361 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 }
363 };
364
365 /// \brief The current state when indenting a unwrapped line.
366 ///
367 /// As the indenting tries different combinations this is copied by value.
368 struct LineState {
369 /// \brief The number of used columns in the current line.
370 unsigned Column;
371
372 /// \brief The token that needs to be next formatted.
373 const AnnotatedToken *NextToken;
374
Daniel Jasperbbc84152013-01-29 11:27:30 +0000375 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000376 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000377 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000378 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000379
380 /// \brief \c true if this line contains a continued for-loop section.
381 bool LineContainsContinuedForLoopSection;
382
Daniel Jasper337816e2013-01-11 10:22:12 +0000383 /// \brief A stack keeping track of properties applying to parenthesis
384 /// levels.
385 std::vector<ParenState> Stack;
386
387 /// \brief Comparison operator to be able to used \c LineState in \c map.
388 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000389 if (Other.NextToken != NextToken)
390 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000391 if (Other.Column != Column)
392 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000393 if (Other.VariablePos != VariablePos)
394 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000395 if (Other.LineContainsContinuedForLoopSection !=
396 LineContainsContinuedForLoopSection)
397 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000398 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000399 }
400 };
401
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000402 /// \brief Appends the next token to \p State and updates information
403 /// necessary for indentation.
404 ///
405 /// Puts the token on the current line if \p Newline is \c true and adds a
406 /// line break and necessary indentation otherwise.
407 ///
408 /// If \p DryRun is \c false, also creates and stores the required
409 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000410 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000411 const AnnotatedToken &Current = *State.NextToken;
412 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000413 assert(State.Stack.size());
414 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000415
Daniel Jasper4b866272013-02-01 11:00:45 +0000416 if (Current.Type == TT_ImplicitStringLiteral) {
417 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];
423 return;
424 }
425
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000427 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000428 if (Current.is(tok::r_brace)) {
429 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000430 } else if (Current.is(tok::string_literal) &&
431 Previous.is(tok::string_literal)) {
432 State.Column = State.Column - Previous.FormatTok.TokenLength;
433 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 State.Stack[ParenLevel].FirstLessLess != 0) {
435 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000436 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000437 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000438 Current.is(tok::period) || Current.is(tok::arrow) ||
439 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000440 // Indent and extra 4 spaces after if we know the current expression is
441 // continued. Don't do that on the top level, as we already indent 4
442 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000443 State.Column = std::max(State.Stack.back().LastSpace,
444 State.Stack.back().Indent) + 4;
445 } else if (Current.Type == TT_ConditionalExpr) {
446 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000447 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
448 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
449 ParenLevel == 0)) {
450 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000451 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
452 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000454 } else if (Previous.Type == TT_BinaryOperator &&
455 State.Stack.back().AssignmentColumn != 0) {
456 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000457 } else if (Current.Type == TT_ObjCSelectorName) {
458 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
459 State.Column =
460 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
461 } else {
462 State.Column = State.Stack.back().Indent;
463 State.Stack.back().ColonPos =
464 State.Column + Current.FormatTok.TokenLength;
465 }
466 } else if (Previous.Type == TT_ObjCMethodExpr) {
467 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000468 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000469 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000470 }
471
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000472 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000473 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000474
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000475 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000476 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000477
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000478 if (!DryRun) {
479 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000480 Whitespaces.replaceWhitespace(Current, 1, State.Column,
481 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000482 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000483 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
484 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000485 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000486
Daniel Jasper337816e2013-01-11 10:22:12 +0000487 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000488 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000489 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000490 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000491 if (Current.is(tok::equal) &&
492 (RootToken.is(tok::kw_for) || ParenLevel == 0))
493 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000494
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000495 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
496 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000497 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000498
Daniel Jasperf7935112012-12-03 18:12:45 +0000499 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000500 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000501
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000502 if (Current.Type == TT_ObjCSelectorName &&
503 State.Stack.back().ColonPos == 0) {
504 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
505 State.Column + Spaces + Current.FormatTok.TokenLength)
506 State.Stack.back().ColonPos =
507 State.Stack.back().Indent + Current.LongestObjCSelectorName;
508 else
509 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000510 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000511 }
512
Daniel Jasperbcab4302013-01-09 10:40:23 +0000513 // FIXME: Do we need to do this for assignments nested in other
514 // expressions?
515 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper38396592013-02-06 15:23:09 +0000516 !isTrailingComment(Current) &&
Daniel Jasper206df732013-01-07 13:08:40 +0000517 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000518 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000519 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000520 if (Current.Type != TT_LineComment &&
521 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
522 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000523 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000524 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000525 State.Stack[ParenLevel].HasMultiParameterLine = true;
526
Daniel Jaspere9de2602012-12-06 09:56:08 +0000527 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000528 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
529 // Treat the condition inside an if as if it was a second function
530 // parameter, i.e. let nested calls have an indent of 4.
531 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000532 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000533 // Top-level spaces are exempt as that mostly leads to better results.
534 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000535 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000536 Previous.Type == TT_ConditionalExpr ||
537 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000538 getPrecedence(Previous) != prec::Assignment)
539 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000540 else if (Previous.ParameterCount > 1 &&
541 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000542 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000543 Previous.Type == TT_TemplateOpener))
544 // If this function has multiple parameters, indent nested calls from
545 // the start of the first parameter.
546 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000547 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000548
549 // If we break after an {, we should also break before the corresponding }.
550 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000551 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000552
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000553 if (State.Stack.back().AvoidBinPacking && Newline &&
554 (Line.First.isNot(tok::kw_for) || ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000555 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000556 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000557 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
558 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000559 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
560 Line.MustBeDeclaration))
Daniel Jasperacc33662013-02-08 08:22:00 +0000561 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000562
Daniel Jaspere941b162013-01-23 10:08:28 +0000563 // Any break on this level means that the parent level has been broken
564 // and we need to avoid bin packing there.
565 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000566 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperacc33662013-02-08 08:22:00 +0000567 State.Stack[i].BreakBeforeParameter = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000568 }
569 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000570
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000571 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000572 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000573
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000574 /// \brief Mark the next token as consumed in \p State and modify its stacks
575 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000576 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000577 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000578 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000579
Daniel Jasper337816e2013-01-11 10:22:12 +0000580 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
581 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000582 if (Current.is(tok::question))
583 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000584 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000585 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000586 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
587 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000588 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000589
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000590 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000591 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000592 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
593 Current.is(tok::l_brace) ||
594 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000595 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000596 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000597 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000598 NewIndent = 2 + State.Stack.back().LastSpace;
599 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000600 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000602 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000603 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000604 State.Stack.push_back(
605 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
606 State.Stack.back().HasMultiParameterLine));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000607 }
608
Daniel Jasperacc33662013-02-08 08:22:00 +0000609 // If this '[' opens an ObjC call, determine whether all parameters fit into
610 // one line and put one per line if they don't.
611 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
612 Current.MatchingParen != NULL) {
613 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
614 State.Stack.back().BreakBeforeParameter = true;
615 }
616
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000617 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000618 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
620 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
621 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000622 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000624
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000625 if (State.NextToken->Children.empty())
626 State.NextToken = NULL;
627 else
628 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000629
630 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000631 }
632
Daniel Jasper2df93312013-01-09 10:16:05 +0000633 unsigned getColumnLimit() {
634 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
635 }
636
Daniel Jasper4b866272013-02-01 11:00:45 +0000637 /// \brief An edge in the solution space starting from the \c LineState and
638 /// inserting a newline dependent on the \c bool.
639 typedef std::pair<bool, const LineState *> Edge;
640
641 /// \brief An item in the prioritized BFS search queue. The \c LineState was
642 /// reached using the \c Edge.
643 typedef std::pair<LineState, Edge> QueueItem;
644
645 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000647 /// This implements a variant of Dijkstra's algorithm on the graph that spans
648 /// the solution space (\c LineStates are the nodes). The algorithm tries to
649 /// find the shortest path (the one with lowest penalty) from \p InitialState
650 /// to a state where all tokens are placed.
651 unsigned analyzeSolutionSpace(const LineState &InitialState) {
652 // Insert start element into queue.
653 std::multimap<unsigned, QueueItem> Queue;
654 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000655 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper4b866272013-02-01 11:00:45 +0000656 std::map<LineState, Edge> Seen;
657
658 // While not empty, take first element and follow edges.
659 while (!Queue.empty()) {
660 unsigned Penalty = Queue.begin()->first;
661 QueueItem Item = Queue.begin()->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000662 if (Item.first.NextToken == NULL) {
663 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000664 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000665 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000666 Queue.erase(Queue.begin());
667
668 if (Seen.find(Item.first) != Seen.end())
669 continue; // State already examined with lower penalty.
670
671 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
672 Item.first,
673 Edge(Item.second.first, Item.second.second))).first->first;
674
675 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
676 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
677 }
678
679 if (Queue.empty())
680 // We were unable to find a solution, do nothing.
681 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000682 return 0;
683
Daniel Jasper4b866272013-02-01 11:00:45 +0000684 // Reconstruct the solution.
685 // FIXME: Add debugging output.
686 Edge *CurrentEdge = &Queue.begin()->second.second;
687 while (CurrentEdge->second != NULL) {
688 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000689 if (CurrentEdge->first) {
690 DEBUG(llvm::errs() << "Penalty for splitting before "
691 << CurrentState.NextToken->FormatTok.Tok.getName()
692 << ": " << CurrentState.NextToken->SplitPenalty
693 << "\n");
694 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000695 addTokenToState(CurrentEdge->first, false, CurrentState);
696 CurrentEdge = &Seen[*CurrentEdge->second];
697 }
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000698 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000699
Daniel Jasper4b866272013-02-01 11:00:45 +0000700 // Return the column after the last token of the solution.
701 return Queue.begin()->second.first.Column;
702 }
703
704 /// \brief Add the following state to the analysis queue \p Queue.
705 ///
706 /// Assume the current state is \p OldState and has been reached with a
707 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
708 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
709 bool NewLine,
710 std::multimap<unsigned, QueueItem> &Queue) {
711 if (NewLine && !canBreak(OldState))
712 return;
713 if (!NewLine && mustBreak(OldState))
714 return;
715 LineState State(OldState);
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000716 if (NewLine)
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000717 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000718 addTokenToState(NewLine, true, State);
Daniel Jasper2df93312013-01-09 10:16:05 +0000719 if (State.Column > getColumnLimit()) {
720 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000721 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000722 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000723 Queue.insert(std::pair<unsigned, QueueItem>(
724 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
725 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000726
Daniel Jasper4b866272013-02-01 11:00:45 +0000727 /// \brief Returns \c true, if a line break after \p State is allowed.
728 bool canBreak(const LineState &State) {
729 if (!State.NextToken->CanBreakBefore &&
730 !(State.NextToken->is(tok::r_brace) &&
731 State.Stack.back().BreakBeforeClosingBrace))
732 return false;
733 // Trying to insert a parameter on a new line if there are already more than
734 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000735 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000736 State.Stack.back().AvoidBinPacking)
737 return false;
738 return true;
739 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000740
Daniel Jasper4b866272013-02-01 11:00:45 +0000741 /// \brief Returns \c true, if a line break after \p State is mandatory.
742 bool mustBreak(const LineState &State) {
743 if (State.NextToken->MustBreakBefore)
744 return true;
745 if (State.NextToken->is(tok::r_brace) &&
746 State.Stack.back().BreakBeforeClosingBrace)
747 return true;
748 if (State.NextToken->Parent->is(tok::semi) &&
749 State.LineContainsContinuedForLoopSection)
750 return true;
751 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000752 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000753 !isTrailingComment(*State.NextToken))
Daniel Jasper4b866272013-02-01 11:00:45 +0000754 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000755 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
756 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000757 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000758 State.NextToken->LongestObjCSelectorName == 0 &&
759 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000760 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000761 if ((State.NextToken->Type == TT_CtorInitializerColon ||
762 (State.NextToken->Parent->ClosesTemplateDeclaration &&
763 State.Stack.size() == 1)))
764 return true;
765 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000766 }
767
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 FormatStyle Style;
769 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000770 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000771 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000773 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000774};
775
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000776class LexerBasedFormatTokenSource : public FormatTokenSource {
777public:
778 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000779 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000780 IdentTable(Lex.getLangOpts()) {
781 Lex.SetKeepWhitespaceMode(true);
782 }
783
784 virtual FormatToken getNextToken() {
785 if (GreaterStashed) {
786 FormatTok.NewlinesBefore = 0;
787 FormatTok.WhiteSpaceStart =
788 FormatTok.Tok.getLocation().getLocWithOffset(1);
789 FormatTok.WhiteSpaceLength = 0;
790 GreaterStashed = false;
791 return FormatTok;
792 }
793
794 FormatTok = FormatToken();
795 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000796 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000797 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000798 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
799 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000800
801 // Consume and record whitespace until we find a significant token.
802 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000803 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +0000804 FormatTok.HasUnescapedNewline =
805 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000806 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
807
808 if (FormatTok.Tok.is(tok::eof))
809 return FormatTok;
810 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000811 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000812 }
Manuel Klimekef920692013-01-07 07:56:50 +0000813
814 // Now FormatTok is the next non-whitespace token.
815 FormatTok.TokenLength = Text.size();
816
Manuel Klimek1abf7892013-01-04 23:34:14 +0000817 // In case the token starts with escaped newlines, we want to
818 // take them into account as whitespace - this pattern is quite frequent
819 // in macro definitions.
820 // FIXME: What do we want to do with other escaped spaces, and escaped
821 // spaces or newlines in the middle of tokens?
822 // FIXME: Add a more explicit test.
823 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000824 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000825 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000826 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000827 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000828 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000829 }
830
831 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000832 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000833 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000834 FormatTok.Tok.setKind(Info.getTokenID());
835 }
836
837 if (FormatTok.Tok.is(tok::greatergreater)) {
838 FormatTok.Tok.setKind(tok::greater);
839 GreaterStashed = true;
840 }
841
842 return FormatTok;
843 }
844
845private:
846 FormatToken FormatTok;
847 bool GreaterStashed;
848 Lexer &Lex;
849 SourceManager &SourceMgr;
850 IdentifierTable IdentTable;
851
852 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000853 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000854 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
855 Tok.getLength());
856 }
857};
858
Daniel Jasperf7935112012-12-03 18:12:45 +0000859class Formatter : public UnwrappedLineConsumer {
860public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000861 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
862 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000863 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000864 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000865 Whitespaces(SourceMgr), Ranges(Ranges) {
866 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000867
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000868 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000869
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000870 void deriveLocalStyle() {
871 unsigned CountBoundToVariable = 0;
872 unsigned CountBoundToType = 0;
873 bool HasCpp03IncompatibleFormat = false;
874 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
875 if (AnnotatedLines[i].First.Children.empty())
876 continue;
877 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
878 while (!Tok->Children.empty()) {
879 if (Tok->Type == TT_PointerOrReference) {
880 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
881 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
882 if (SpacesBefore && !SpacesAfter)
883 ++CountBoundToVariable;
884 else if (!SpacesBefore && SpacesAfter)
885 ++CountBoundToType;
886 }
887
888 if (Tok->Type == TT_TemplateCloser && Tok->Parent->Type ==
889 TT_TemplateCloser && Tok->FormatTok.WhiteSpaceLength == 0)
890 HasCpp03IncompatibleFormat = true;
891 Tok = &Tok->Children[0];
892 }
893 }
894 if (Style.DerivePointerBinding) {
895 if (CountBoundToType > CountBoundToVariable)
896 Style.PointerBindsToType = true;
897 else if (CountBoundToType < CountBoundToVariable)
898 Style.PointerBindsToType = false;
899 }
900 if (Style.Standard == FormatStyle::LS_Auto) {
901 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
902 : FormatStyle::LS_Cpp03;
903 }
904 }
905
Daniel Jasperf7935112012-12-03 18:12:45 +0000906 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000907 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000908 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000909 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000910 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000911 TokenAnnotator Annotator(Style, SourceMgr, Lex);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000912 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000913 Annotator.annotate(AnnotatedLines[i]);
914 }
915 deriveLocalStyle();
916 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
917 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000918 }
919 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
920 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000921 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000922 const AnnotatedLine &TheLine = *I;
923 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000924 unsigned Indent =
925 formatFirstToken(TheLine.First, TheLine.Level,
926 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000927 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000928 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000929 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000930 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000931 PreviousEndOfLineColumn = Formatter.format();
932 } else {
933 // If we did not reformat this unwrapped line, the column at the end of
934 // the last token is unchanged - thus, we can calculate the end of the
935 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000936 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000937 SourceMgr.getSpellingColumnNumber(
938 TheLine.Last->FormatTok.Tok.getLocation()) +
939 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000940 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000941 }
942 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000943 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +0000944 }
945
946private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000947 /// \brief Tries to merge lines into one.
948 ///
949 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
950 /// if possible; note that \c I will be incremented when lines are merged.
951 ///
952 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000953 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000954 std::vector<AnnotatedLine>::iterator &I,
955 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000956 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
957
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000958 // We can never merge stuff if there are trailing line comments.
959 if (I->Last->Type == TT_LineComment)
960 return;
961
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000962 // Check whether the UnwrappedLine can be put onto a single line. If
963 // so, this is bound to be the optimal solution (by definition) and we
964 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000965 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000966 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000967 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +0000968
Daniel Jasperd41ee2d2013-01-21 14:18:28 +0000969 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000970 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +0000971
Daniel Jasper25837aa2013-01-14 14:14:23 +0000972 if (I->Last->is(tok::l_brace)) {
973 tryMergeSimpleBlock(I, E, Limit);
974 } else if (I->First.is(tok::kw_if)) {
975 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +0000976 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
977 I->First.FormatTok.IsFirst)) {
978 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +0000979 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000980 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +0000981 }
982
Daniel Jasper39825ea2013-01-14 15:40:57 +0000983 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
984 std::vector<AnnotatedLine>::iterator E,
985 unsigned Limit) {
986 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +0000987 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
988 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000989 if (I + 2 != E && (I + 2)->InPPDirective &&
990 !(I + 2)->First.FormatTok.HasUnescapedNewline)
991 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000992 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000993 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +0000994 join(Line, *(++I));
995 }
996
Daniel Jasper25837aa2013-01-14 14:14:23 +0000997 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
998 std::vector<AnnotatedLine>::iterator E,
999 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001000 if (!Style.AllowShortIfStatementsOnASingleLine)
1001 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001002 if ((I + 1)->InPPDirective != I->InPPDirective ||
1003 ((I + 1)->InPPDirective &&
1004 (I + 1)->First.FormatTok.HasUnescapedNewline))
1005 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001006 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001007 if (Line.Last->isNot(tok::r_paren))
1008 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001009 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001010 return;
1011 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1012 return;
1013 // Only inline simple if's (no nested if or else).
1014 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1015 return;
1016 join(Line, *(++I));
1017 }
1018
1019 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001020 std::vector<AnnotatedLine>::iterator E,
1021 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001022 // First, check that the current line allows merging. This is the case if
1023 // we're not in a control flow statement and the last token is an opening
1024 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001025 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001026 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001027 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1028 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1029 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1030 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001031 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001032 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1033 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001034 if (!AllowedTokens)
1035 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001036
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001037 AnnotatedToken *Tok = &(I + 1)->First;
1038 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1039 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1040 Tok->SpaceRequiredBefore = false;
1041 join(Line, *(I + 1));
1042 I += 1;
1043 } else {
1044 // Check that we still have three lines and they fit into the limit.
1045 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1046 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001047 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001048
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001049 // Second, check that the next line does not contain any braces - if it
1050 // does, readability declines when putting it into a single line.
1051 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1052 return;
1053 do {
1054 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1055 return;
1056 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1057 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001058
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001059 // Last, check that the third line contains a single closing brace.
1060 Tok = &(I + 2)->First;
1061 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1062 Tok->MustBreakBefore)
1063 return;
1064
1065 join(Line, *(I + 1));
1066 join(Line, *(I + 2));
1067 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001068 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001069 }
1070
1071 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1072 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001073 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1074 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001075 }
1076
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001077 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1078 A.Last->Children.push_back(B.First);
1079 while (!A.Last->Children.empty()) {
1080 A.Last->Children[0].Parent = A.Last;
1081 A.Last = &A.Last->Children[0];
1082 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001083 }
1084
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001085 bool touchesRanges(const AnnotatedLine &TheLine) {
1086 const FormatToken *First = &TheLine.First.FormatTok;
1087 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001088 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001089 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001090 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001091 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1092 Ranges[i].getBegin()) &&
1093 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1094 LineRange.getBegin()))
1095 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001096 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001097 return false;
1098 }
1099
1100 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001101 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001102 }
1103
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001104 /// \brief Add a new line and the required indent before the first Token
1105 /// of the \c UnwrappedLine if there was no structural parsing error.
1106 /// Returns the indent level of the \c UnwrappedLine.
1107 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1108 bool InPPDirective,
1109 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001110 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001111 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1112 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1113
Daniel Jasperbbc84152013-01-29 11:27:30 +00001114 unsigned Newlines =
1115 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001116 if (Newlines == 0 && !Tok.IsFirst)
1117 Newlines = 1;
1118 unsigned Indent = Level * 2;
1119
1120 bool IsAccessModifier = false;
1121 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1122 RootToken.is(tok::kw_private))
1123 IsAccessModifier = true;
1124 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1125 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1126 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1127 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1128 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1129 IsAccessModifier = true;
1130
1131 if (IsAccessModifier &&
1132 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1133 Indent += Style.AccessModifierOffset;
1134 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001135 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001136 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001137 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1138 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001139 }
1140 return Indent;
1141 }
1142
Alexander Kornienko116ba682013-01-14 11:34:14 +00001143 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001144 FormatStyle Style;
1145 Lexer &Lex;
1146 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001147 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001148 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001149 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001150 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001151};
1152
Daniel Jasperbbc84152013-01-29 11:27:30 +00001153tooling::Replacements
1154reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1155 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001156 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001157 OwningPtr<DiagnosticConsumer> DiagPrinter;
1158 if (DiagClient == 0) {
1159 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1160 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1161 DiagClient = DiagPrinter.get();
1162 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001163 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001164 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001165 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001166 Diagnostics.setSourceManager(&SourceMgr);
1167 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001168 return formatter.format();
1169}
1170
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001171LangOptions getFormattingLangOpts() {
1172 LangOptions LangOpts;
1173 LangOpts.CPlusPlus = 1;
1174 LangOpts.CPlusPlus11 = 1;
1175 LangOpts.Bool = 1;
1176 LangOpts.ObjC1 = 1;
1177 LangOpts.ObjC2 = 1;
1178 return LangOpts;
1179}
1180
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001181} // namespace format
1182} // namespace clang