blob: 4b63aa93220fc3b1ccbb3931214b438224906c7a [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 Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperf7935112012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000064 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper1b750ed2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000077 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
78 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000079 return ChromiumStyle;
80}
81
Daniel Jasper94f0e132013-02-06 20:07:35 +000082static bool isTrailingComment(const AnnotatedToken &Tok) {
83 return Tok.is(tok::comment) &&
84 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
85}
86
Daniel Jasperacc33662013-02-08 08:22:00 +000087// Returns the length of everything up to the first possible line break after
88// the ), ], } or > matching \c Tok.
89static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
90 if (Tok.MatchingParen == NULL)
91 return 0;
92 AnnotatedToken *End = Tok.MatchingParen;
93 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
94 End = &End->Children[0];
95 }
96 return End->TotalLength - Tok.TotalLength + 1;
97}
98
Daniel Jasperaa701fa2013-01-18 08:44:07 +000099/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000100///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000101/// This includes special handling for certain constructs, e.g. the alignment of
102/// trailing line comments.
103class WhitespaceManager {
104public:
105 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
106
107 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
108 /// each \c AnnotatedToken.
109 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
110 unsigned Spaces, unsigned WhitespaceStartColumn,
111 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000112 // 2+ newlines mean an empty line separating logic scopes.
113 if (NewLines >= 2)
114 alignComments();
115
116 // Align line comments if they are trailing or if they continue other
117 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000118 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000119 if (Style.ColumnLimit >=
120 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
121 Comments.push_back(StoredComment());
122 Comments.back().Tok = Tok.FormatTok;
123 Comments.back().Spaces = Spaces;
124 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000125 if (NewLines == 0)
126 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
127 else
128 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000129 Comments.back().MaxColumn =
Daniel Jasper525264c2013-02-13 19:25:54 +0000130 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 return;
132 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000134
135 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000136 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000137 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000138 storeReplacement(Tok.FormatTok,
139 std::string(NewLines, '\n') + std::string(Spaces, ' '));
140 }
141
142 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
143 /// backslashes to escape newlines inside a preprocessor directive.
144 ///
145 /// This function and \c replaceWhitespace have the same behavior if
146 /// \c Newlines == 0.
147 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
148 unsigned Spaces, unsigned WhitespaceStartColumn,
149 const FormatStyle &Style) {
150 std::string NewLineText;
151 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000152 unsigned Offset =
153 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000154 for (unsigned i = 0; i < NewLines; ++i) {
155 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
156 NewLineText += "\\\n";
157 Offset = 0;
158 }
159 }
160 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
161 }
162
163 /// \brief Returns all the \c Replacements created during formatting.
164 const tooling::Replacements &generateReplacements() {
165 alignComments();
166 return Replaces;
167 }
168
169private:
170 /// \brief Structure to store a comment for later layout and alignment.
171 struct StoredComment {
172 FormatToken Tok;
173 unsigned MinColumn;
174 unsigned MaxColumn;
175 unsigned NewLines;
176 unsigned Spaces;
177 };
178 SmallVector<StoredComment, 16> Comments;
179 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
180
181 /// \brief Try to align all stashed comments.
182 void alignComments() {
183 unsigned MinColumn = 0;
184 unsigned MaxColumn = UINT_MAX;
185 comment_iterator Start = Comments.begin();
186 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
187 ++I) {
188 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
189 alignComments(Start, I, MinColumn);
190 MinColumn = I->MinColumn;
191 MaxColumn = I->MaxColumn;
192 Start = I;
193 } else {
194 MinColumn = std::max(MinColumn, I->MinColumn);
195 MaxColumn = std::min(MaxColumn, I->MaxColumn);
196 }
197 }
198 alignComments(Start, Comments.end(), MinColumn);
199 Comments.clear();
200 }
201
202 /// \brief Put all the comments between \p I and \p E into \p Column.
203 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
204 while (I != E) {
205 unsigned Spaces = I->Spaces + Column - I->MinColumn;
206 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper400adc62013-02-08 15:28:42 +0000207 std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000208 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000209 }
210 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000211
212 /// \brief Stores \p Text as the replacement for the whitespace in front of
213 /// \p Tok.
214 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000215 // Don't create a replacement, if it does not change anything.
216 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
217 Tok.WhiteSpaceLength) == Text)
218 return;
219
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000220 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
221 Tok.WhiteSpaceLength, Text));
222 }
223
224 SourceManager &SourceMgr;
225 tooling::Replacements Replaces;
226};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000227
Daniel Jasperf7935112012-12-03 18:12:45 +0000228class UnwrappedLineFormatter {
229public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000230 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000231 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000232 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000233 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000234 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000235 FirstIndent(FirstIndent), RootToken(RootToken),
Manuel Klimekaf491072013-02-13 10:54:19 +0000236 Whitespaces(Whitespaces), Count(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000237 }
238
Manuel Klimek1abf7892013-01-04 23:34:14 +0000239 /// \brief Formats an \c UnwrappedLine.
240 ///
241 /// \returns The column after the last token in the last line of the
242 /// \c UnwrappedLine.
243 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000244 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000245 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000246 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000247 State.NextToken = &RootToken;
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000248 State.Stack.push_back(
249 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
250 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000251 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000252 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000253 State.ParenLevel = 0;
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 Jasper400adc62013-02-08 15:28:42 +0000290 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
291 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000292 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper54a86022013-02-15 11:07:25 +0000293 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
294 BreakBeforeThirdOperand(false) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000295 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000296
Daniel Jasperf7935112012-12-03 18:12:45 +0000297 /// \brief The position to which a specific parenthesis level needs to be
298 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000299 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000300
Daniel Jaspere9de2602012-12-06 09:56:08 +0000301 /// \brief The position of the last space on each level.
302 ///
303 /// Used e.g. to break like:
304 /// functionCall(Parameter, otherCall(
305 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000306 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000307
Daniel Jaspere9de2602012-12-06 09:56:08 +0000308 /// \brief The position the first "<<" operator encountered on each level.
309 ///
310 /// Used to align "<<" operators. 0 if no such operator has been encountered
311 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000312 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000313
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000314 /// \brief Whether a newline needs to be inserted before the block's closing
315 /// brace.
316 ///
317 /// We only want to insert a newline before the closing brace if there also
318 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000319 bool BreakBeforeClosingBrace;
320
Daniel Jasperca6623b2013-01-28 12:45:14 +0000321 /// \brief The column of a \c ? in a conditional expression;
322 unsigned QuestionColumn;
323
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000324 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
325 /// lines, in this context.
326 bool AvoidBinPacking;
327
328 /// \brief Break after the next comma (or all the commas in this context if
329 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000330 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000331
332 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000333 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000334
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000335 /// \brief The position of the colon in an ObjC method declaration/call.
336 unsigned ColonPos;
Daniel Jasper54a86022013-02-15 11:07:25 +0000337
338 /// \brief Break before third operand in ternary expression.
339 bool BreakBeforeThirdOperand;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000340
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 bool operator<(const ParenState &Other) const {
342 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000343 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000344 if (LastSpace != Other.LastSpace)
345 return LastSpace < Other.LastSpace;
346 if (FirstLessLess != Other.FirstLessLess)
347 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000348 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
349 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000350 if (QuestionColumn != Other.QuestionColumn)
351 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000352 if (AvoidBinPacking != Other.AvoidBinPacking)
353 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000354 if (BreakBeforeParameter != Other.BreakBeforeParameter)
355 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000356 if (HasMultiParameterLine != Other.HasMultiParameterLine)
357 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000358 if (ColonPos != Other.ColonPos)
359 return ColonPos < Other.ColonPos;
Daniel Jasper54a86022013-02-15 11:07:25 +0000360 if (BreakBeforeThirdOperand != Other.BreakBeforeThirdOperand)
361 return BreakBeforeThirdOperand;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000362 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000363 }
364 };
365
366 /// \brief The current state when indenting a unwrapped line.
367 ///
368 /// As the indenting tries different combinations this is copied by value.
369 struct LineState {
370 /// \brief The number of used columns in the current line.
371 unsigned Column;
372
373 /// \brief The token that needs to be next formatted.
374 const AnnotatedToken *NextToken;
375
Daniel Jasperbbc84152013-01-29 11:27:30 +0000376 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000377 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000378 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000379 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000380
381 /// \brief \c true if this line contains a continued for-loop section.
382 bool LineContainsContinuedForLoopSection;
383
Daniel Jasper400adc62013-02-08 15:28:42 +0000384 /// \brief The level of nesting inside (), [], <> and {}.
385 unsigned ParenLevel;
386
Daniel Jasper337816e2013-01-11 10:22:12 +0000387 /// \brief A stack keeping track of properties applying to parenthesis
388 /// levels.
389 std::vector<ParenState> Stack;
390
391 /// \brief Comparison operator to be able to used \c LineState in \c map.
392 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000393 if (Other.NextToken != NextToken)
394 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000395 if (Other.Column != Column)
396 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000397 if (Other.VariablePos != VariablePos)
398 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000399 if (Other.LineContainsContinuedForLoopSection !=
400 LineContainsContinuedForLoopSection)
401 return LineContainsContinuedForLoopSection;
Daniel Jasper400adc62013-02-08 15:28:42 +0000402 if (Other.ParenLevel != ParenLevel)
403 return Other.ParenLevel < ParenLevel;
Daniel Jasper337816e2013-01-11 10:22:12 +0000404 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000405 }
406 };
407
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000408 /// \brief Appends the next token to \p State and updates information
409 /// necessary for indentation.
410 ///
411 /// Puts the token on the current line if \p Newline is \c true and adds a
412 /// line break and necessary indentation otherwise.
413 ///
414 /// If \p DryRun is \c false, also creates and stores the required
415 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000416 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000417 const AnnotatedToken &Current = *State.NextToken;
418 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000419 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000420
Daniel Jasper4b866272013-02-01 11:00:45 +0000421 if (Current.Type == TT_ImplicitStringLiteral) {
422 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
423 State.NextToken->FormatTok.TokenLength;
424 if (State.NextToken->Children.empty())
425 State.NextToken = NULL;
426 else
427 State.NextToken = &State.NextToken->Children[0];
428 return;
429 }
430
Daniel Jasperf7935112012-12-03 18:12:45 +0000431 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000432 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000433 if (Current.is(tok::r_brace)) {
434 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000435 } else if (Current.is(tok::string_literal) &&
436 Previous.is(tok::string_literal)) {
437 State.Column = State.Column - Previous.FormatTok.TokenLength;
438 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000439 State.Stack.back().FirstLessLess != 0) {
440 State.Column = State.Stack.back().FirstLessLess;
441 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000442 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000443 Current.is(tok::period) || Current.is(tok::arrow) ||
444 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000445 // Indent and extra 4 spaces after if we know the current expression is
446 // continued. Don't do that on the top level, as we already indent 4
447 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000448 State.Column = std::max(State.Stack.back().LastSpace,
449 State.Stack.back().Indent) + 4;
450 } else if (Current.Type == TT_ConditionalExpr) {
451 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000452 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000453 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
454 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000455 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000456 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
457 Current.Type == TT_StartOfName) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000458 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000459 } else if (Current.Type == TT_ObjCSelectorName) {
460 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
461 State.Column =
462 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
463 } else {
464 State.Column = State.Stack.back().Indent;
465 State.Stack.back().ColonPos =
466 State.Column + Current.FormatTok.TokenLength;
467 }
468 } else if (Previous.Type == TT_ObjCMethodExpr) {
469 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000470 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000471 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000472 }
473
Daniel Jasper54a86022013-02-15 11:07:25 +0000474 if (Current.is(tok::question))
475 State.Stack.back().BreakBeforeThirdOperand = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000476 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000477 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000478
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000479 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000480 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000481
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000482 if (!DryRun) {
483 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000484 Whitespaces.replaceWhitespace(Current, 1, State.Column,
485 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000486 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000487 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
488 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000489 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000490
Daniel Jasper400adc62013-02-08 15:28:42 +0000491 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000492 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000493 State.Stack.back().Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000494 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000495 if (Current.is(tok::equal) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000496 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000497 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000498
Daniel Jaspereef30492013-02-11 12:36:37 +0000499 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000500
Daniel Jasperf7935112012-12-03 18:12:45 +0000501 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000502 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000503
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000504 if (Current.Type == TT_ObjCSelectorName &&
505 State.Stack.back().ColonPos == 0) {
506 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
507 State.Column + Spaces + Current.FormatTok.TokenLength)
508 State.Stack.back().ColonPos =
509 State.Stack.back().Indent + Current.LongestObjCSelectorName;
510 else
511 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000512 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000513 }
514
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000515 if (Current.Type != TT_LineComment &&
516 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
517 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000518 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000519 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000520 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000521
Daniel Jaspere9de2602012-12-06 09:56:08 +0000522 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000523 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
524 // Treat the condition inside an if as if it was a second function
525 // parameter, i.e. let nested calls have an indent of 4.
526 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000527 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000528 // Top-level spaces are exempt as that mostly leads to better results.
529 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000530 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000531 Previous.Type == TT_ConditionalExpr ||
532 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000533 getPrecedence(Previous) != prec::Assignment)
534 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000535 else if (Previous.Type == TT_InheritanceColon)
536 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000537 else if (Previous.ParameterCount > 1 &&
538 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000539 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000540 Previous.Type == TT_TemplateOpener))
541 // If this function has multiple parameters, indent nested calls from
542 // the start of the first parameter.
543 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000544 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000545
546 // If we break after an {, we should also break before the corresponding }.
547 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000548 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000549
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000550 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000551 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000552 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000553 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000554 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
555 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000556 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
557 Line.MustBeDeclaration))
Daniel Jasperacc33662013-02-08 08:22:00 +0000558 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000559
Daniel Jaspere941b162013-01-23 10:08:28 +0000560 // Any break on this level means that the parent level has been broken
561 // and we need to avoid bin packing there.
562 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000563 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperacc33662013-02-08 08:22:00 +0000564 State.Stack[i].BreakBeforeParameter = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000565 }
566 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000567
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000568 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000569 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000570
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571 /// \brief Mark the next token as consumed in \p State and modify its stacks
572 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000573 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000574 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000575 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000576
Daniel Jaspereead02b2013-02-14 08:42:54 +0000577 if (Current.Type == TT_InheritanceColon)
578 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000579 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
580 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000581 if (Current.is(tok::question))
582 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000583 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000584 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000585 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
586 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000587 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000588
Daniel Jasper400adc62013-02-08 15:28:42 +0000589 // Insert scopes created by fake parenthesis.
590 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
591 ParenState NewParenState = State.Stack.back();
592 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
593 State.Stack.push_back(NewParenState);
594 }
595
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000596 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000597 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000598 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
599 Current.is(tok::l_brace) ||
600 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000602 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000603 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000604 NewIndent = 2 + State.Stack.back().LastSpace;
605 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000606 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000607 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000608 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000609 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000610 State.Stack.push_back(
611 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
612 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000613 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000614 }
615
Daniel Jasperacc33662013-02-08 08:22:00 +0000616 // If this '[' opens an ObjC call, determine whether all parameters fit into
617 // one line and put one per line if they don't.
618 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
619 Current.MatchingParen != NULL) {
620 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
621 State.Stack.back().BreakBeforeParameter = true;
622 }
623
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000624 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000625 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000626 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
627 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
628 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000629 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000630 --State.ParenLevel;
631 }
632
633 // Remove scopes created by fake parenthesis.
634 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
635 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000637
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000638 if (State.NextToken->Children.empty())
639 State.NextToken = NULL;
640 else
641 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000642
643 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000644 }
645
Daniel Jasper2df93312013-01-09 10:16:05 +0000646 unsigned getColumnLimit() {
647 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
648 }
649
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000650 /// \brief An edge in the solution space from \c Previous->State to \c State,
651 /// inserting a newline dependent on the \c NewLine.
652 struct StateNode {
653 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
654 : State(State), NewLine(NewLine), Previous(Previous) {
655 }
656 LineState State;
657 bool NewLine;
658 StateNode *Previous;
659 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000660
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000661 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
662 ///
663 /// In case of equal penalties, we want to prefer states that were inserted
664 /// first. During state generation we make sure that we insert states first
665 /// that break the line as late as possible.
666 typedef std::pair<unsigned, unsigned> OrderedPenalty;
667
668 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
669 /// \c State has the given \c OrderedPenalty.
670 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
671
672 /// \brief The BFS queue type.
673 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
674 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000675
676 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000677 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000678 /// This implements a variant of Dijkstra's algorithm on the graph that spans
679 /// the solution space (\c LineStates are the nodes). The algorithm tries to
680 /// find the shortest path (the one with lowest penalty) from \p InitialState
681 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000682 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000683 std::set<LineState> Seen;
684
Daniel Jasper4b866272013-02-01 11:00:45 +0000685 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000686 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000687 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
688 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
689 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000690
691 // While not empty, take first element and follow edges.
692 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000693 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000694 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000695 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000696 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000697 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000698 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000699 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000700
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000701 if (!Seen.insert(Node->State).second)
702 // State already examined with lower penalty.
703 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000704
Manuel Klimekaf491072013-02-13 10:54:19 +0000705 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
706 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000707 }
708
709 if (Queue.empty())
710 // We were unable to find a solution, do nothing.
711 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000712 return 0;
713
Daniel Jasper4b866272013-02-01 11:00:45 +0000714 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000715 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000716 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000717
Daniel Jasper4b866272013-02-01 11:00:45 +0000718 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000719 return Queue.top().second->State.Column;
720 }
721
722 void reconstructPath(LineState &State, StateNode *Current) {
723 // FIXME: This recursive implementation limits the possible number
724 // of tokens per line if compiled into a binary with small stack space.
725 // To become more independent of stack frame limitations we would need
726 // to also change the TokenAnnotator.
727 if (Current->Previous == NULL)
728 return;
729 reconstructPath(State, Current->Previous);
730 DEBUG({
731 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000732 llvm::errs()
733 << "Penalty for splitting before "
734 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
735 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000736 }
737 });
738 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000739 }
740
Manuel Klimekaf491072013-02-13 10:54:19 +0000741 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000742 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000743 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000744 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000745 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
746 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000747 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000748 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000749 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000750 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000751 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000752 Penalty += PreviousNode->State.NextToken->SplitPenalty;
753
754 StateNode *Node = new (Allocator.Allocate())
755 StateNode(PreviousNode->State, NewLine, PreviousNode);
756 addTokenToState(NewLine, true, Node->State);
757 if (Node->State.Column > getColumnLimit()) {
758 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000759 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000760 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000761
762 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
763 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000764 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000765
Daniel Jasper4b866272013-02-01 11:00:45 +0000766 /// \brief Returns \c true, if a line break after \p State is allowed.
767 bool canBreak(const LineState &State) {
768 if (!State.NextToken->CanBreakBefore &&
769 !(State.NextToken->is(tok::r_brace) &&
770 State.Stack.back().BreakBeforeClosingBrace))
771 return false;
772 // Trying to insert a parameter on a new line if there are already more than
773 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000774 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000775 State.Stack.back().AvoidBinPacking)
776 return false;
777 return true;
778 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000779
Daniel Jasper4b866272013-02-01 11:00:45 +0000780 /// \brief Returns \c true, if a line break after \p State is mandatory.
781 bool mustBreak(const LineState &State) {
782 if (State.NextToken->MustBreakBefore)
783 return true;
784 if (State.NextToken->is(tok::r_brace) &&
785 State.Stack.back().BreakBeforeClosingBrace)
786 return true;
787 if (State.NextToken->Parent->is(tok::semi) &&
788 State.LineContainsContinuedForLoopSection)
789 return true;
790 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000791 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000792 !isTrailingComment(*State.NextToken) &&
793 State.NextToken->isNot(tok::r_paren))
Daniel Jasper4b866272013-02-01 11:00:45 +0000794 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000795 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
796 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000797 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000798 State.NextToken->LongestObjCSelectorName == 0 &&
799 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000800 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000801 if ((State.NextToken->Type == TT_CtorInitializerColon ||
802 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000803 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000804 return true;
Daniel Jasper54a86022013-02-15 11:07:25 +0000805 if (State.NextToken->is(tok::colon) &&
806 State.Stack.back().BreakBeforeThirdOperand)
807 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000808 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000809 }
810
Daniel Jasperf7935112012-12-03 18:12:45 +0000811 FormatStyle Style;
812 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000813 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000814 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000815 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000816 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000817
818 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
819 QueueType Queue;
820 // Increasing count of \c StateNode items we have created. This is used
821 // to create a deterministic order independent of the container.
822 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000823};
824
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000825class LexerBasedFormatTokenSource : public FormatTokenSource {
826public:
827 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000828 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000829 IdentTable(Lex.getLangOpts()) {
830 Lex.SetKeepWhitespaceMode(true);
831 }
832
833 virtual FormatToken getNextToken() {
834 if (GreaterStashed) {
835 FormatTok.NewlinesBefore = 0;
836 FormatTok.WhiteSpaceStart =
837 FormatTok.Tok.getLocation().getLocWithOffset(1);
838 FormatTok.WhiteSpaceLength = 0;
839 GreaterStashed = false;
840 return FormatTok;
841 }
842
843 FormatTok = FormatToken();
844 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000845 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000846 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000847 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
848 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000849
850 // Consume and record whitespace until we find a significant token.
851 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000852 unsigned Newlines = Text.count('\n');
853 unsigned EscapedNewlines = Text.count("\\\n");
854 FormatTok.NewlinesBefore += Newlines;
855 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000856 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
857
858 if (FormatTok.Tok.is(tok::eof))
859 return FormatTok;
860 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000861 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000862 }
Manuel Klimekef920692013-01-07 07:56:50 +0000863
864 // Now FormatTok is the next non-whitespace token.
865 FormatTok.TokenLength = Text.size();
866
Manuel Klimek1abf7892013-01-04 23:34:14 +0000867 // In case the token starts with escaped newlines, we want to
868 // take them into account as whitespace - this pattern is quite frequent
869 // in macro definitions.
870 // FIXME: What do we want to do with other escaped spaces, and escaped
871 // spaces or newlines in the middle of tokens?
872 // FIXME: Add a more explicit test.
873 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000874 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000875 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000876 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000877 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000878 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000879 }
880
881 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000882 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000883 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000884 FormatTok.Tok.setKind(Info.getTokenID());
885 }
886
887 if (FormatTok.Tok.is(tok::greatergreater)) {
888 FormatTok.Tok.setKind(tok::greater);
889 GreaterStashed = true;
890 }
891
892 return FormatTok;
893 }
894
Nico Weber29f9dea2013-02-11 15:32:15 +0000895 IdentifierTable &getIdentTable() { return IdentTable; }
896
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000897private:
898 FormatToken FormatTok;
899 bool GreaterStashed;
900 Lexer &Lex;
901 SourceManager &SourceMgr;
902 IdentifierTable IdentTable;
903
904 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000905 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000906 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
907 Tok.getLength());
908 }
909};
910
Daniel Jasperf7935112012-12-03 18:12:45 +0000911class Formatter : public UnwrappedLineConsumer {
912public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000913 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
914 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000916 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000917 Whitespaces(SourceMgr), Ranges(Ranges) {
918 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000919
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000920 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000921
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000922 void deriveLocalStyle() {
923 unsigned CountBoundToVariable = 0;
924 unsigned CountBoundToType = 0;
925 bool HasCpp03IncompatibleFormat = false;
926 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
927 if (AnnotatedLines[i].First.Children.empty())
928 continue;
929 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
930 while (!Tok->Children.empty()) {
931 if (Tok->Type == TT_PointerOrReference) {
932 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
933 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
934 if (SpacesBefore && !SpacesAfter)
935 ++CountBoundToVariable;
936 else if (!SpacesBefore && SpacesAfter)
937 ++CountBoundToType;
938 }
939
Daniel Jasper400adc62013-02-08 15:28:42 +0000940 if (Tok->Type == TT_TemplateCloser &&
941 Tok->Parent->Type == TT_TemplateCloser &&
942 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000943 HasCpp03IncompatibleFormat = true;
944 Tok = &Tok->Children[0];
945 }
946 }
947 if (Style.DerivePointerBinding) {
948 if (CountBoundToType > CountBoundToVariable)
949 Style.PointerBindsToType = true;
950 else if (CountBoundToType < CountBoundToVariable)
951 Style.PointerBindsToType = false;
952 }
953 if (Style.Standard == FormatStyle::LS_Auto) {
954 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
955 : FormatStyle::LS_Cpp03;
956 }
957 }
958
Daniel Jasperf7935112012-12-03 18:12:45 +0000959 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000960 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000961 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000962 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000963 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +0000964 TokenAnnotator Annotator(Style, SourceMgr, Lex,
965 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000966 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000967 Annotator.annotate(AnnotatedLines[i]);
968 }
969 deriveLocalStyle();
970 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
971 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000972 }
Manuel Klimekb95f5452013-02-08 17:38:27 +0000973 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +0000974 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000975 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
976 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000977 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000978 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +0000979 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +0000980 while (IndentForLevel.size() <= TheLine.Level)
981 IndentForLevel.push_back(-1);
982 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000983 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasper24570102013-02-14 09:58:41 +0000984 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +0000985 unsigned Indent = LevelIndent;
986 if (static_cast<int>(Indent) + Offset >= 0)
987 Indent += Offset;
988 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
989 StructuralError) {
990 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
991 TheLine.First.FormatTok.Tok.getLocation()) - 1;
992 } else {
993 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
994 PreviousEndOfLineColumn);
995 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000996 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000997 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000998 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000999 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001000 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001001 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001002 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001003 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001004 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1005 TheLine.First.FormatTok.IsFirst) {
1006 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1007 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1008 unsigned LevelIndent = Indent;
1009 if (static_cast<int>(LevelIndent) - Offset >= 0)
1010 LevelIndent -= Offset;
1011 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001012
1013 // Remove trailing whitespace of the previous line if it was touched.
1014 if (PreviousLineWasTouched)
1015 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1016 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001017 }
Daniel Jasper24570102013-02-14 09:58:41 +00001018 // If we did not reformat this unwrapped line, the column at the end of
1019 // the last token is unchanged - thus, we can calculate the end of the
1020 // last token.
1021 PreviousEndOfLineColumn =
1022 SourceMgr.getSpellingColumnNumber(
1023 TheLine.Last->FormatTok.Tok.getLocation()) +
1024 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1025 SourceMgr, Lex.getLangOpts()) - 1;
1026 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001027 }
1028 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001029 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 }
1031
1032private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001033 /// \brief Get the indent of \p Level from \p IndentForLevel.
1034 ///
1035 /// \p IndentForLevel must contain the indent for the level \c l
1036 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1037 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001038 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001039 if (IndentForLevel[Level] != -1)
1040 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001041 if (Level == 0)
1042 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001043 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001044 }
1045
1046 /// \brief Get the offset of the line relatively to the level.
1047 ///
1048 /// For example, 'public:' labels in classes are offset by 1 or 2
1049 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001050 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001051 bool IsAccessModifier = false;
1052 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1053 RootToken.is(tok::kw_private))
1054 IsAccessModifier = true;
1055 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1056 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1057 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1058 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1059 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1060 IsAccessModifier = true;
1061
1062 if (IsAccessModifier)
1063 return Style.AccessModifierOffset;
1064 return 0;
1065 }
1066
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001067 /// \brief Tries to merge lines into one.
1068 ///
1069 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1070 /// if possible; note that \c I will be incremented when lines are merged.
1071 ///
1072 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001073 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001074 std::vector<AnnotatedLine>::iterator &I,
1075 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001076 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1077
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001078 // We can never merge stuff if there are trailing line comments.
1079 if (I->Last->Type == TT_LineComment)
1080 return;
1081
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001082 // Check whether the UnwrappedLine can be put onto a single line. If
1083 // so, this is bound to be the optimal solution (by definition) and we
1084 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001085 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001086 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001087 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001088
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001089 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001090 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001091
Daniel Jasper25837aa2013-01-14 14:14:23 +00001092 if (I->Last->is(tok::l_brace)) {
1093 tryMergeSimpleBlock(I, E, Limit);
1094 } else if (I->First.is(tok::kw_if)) {
1095 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001096 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1097 I->First.FormatTok.IsFirst)) {
1098 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001099 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001100 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001101 }
1102
Daniel Jasper39825ea2013-01-14 15:40:57 +00001103 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1104 std::vector<AnnotatedLine>::iterator E,
1105 unsigned Limit) {
1106 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001107 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1108 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001109 if (I + 2 != E && (I + 2)->InPPDirective &&
1110 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1111 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001112 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001113 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001114 join(Line, *(++I));
1115 }
1116
Daniel Jasper25837aa2013-01-14 14:14:23 +00001117 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1118 std::vector<AnnotatedLine>::iterator E,
1119 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001120 if (!Style.AllowShortIfStatementsOnASingleLine)
1121 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001122 if ((I + 1)->InPPDirective != I->InPPDirective ||
1123 ((I + 1)->InPPDirective &&
1124 (I + 1)->First.FormatTok.HasUnescapedNewline))
1125 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001126 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001127 if (Line.Last->isNot(tok::r_paren))
1128 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001129 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001130 return;
1131 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1132 return;
1133 // Only inline simple if's (no nested if or else).
1134 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1135 return;
1136 join(Line, *(++I));
1137 }
1138
1139 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001140 std::vector<AnnotatedLine>::iterator E,
1141 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001142 // First, check that the current line allows merging. This is the case if
1143 // we're not in a control flow statement and the last token is an opening
1144 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001145 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001146 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001147 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1148 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1149 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1150 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001151 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001152 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1153 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001154 if (!AllowedTokens)
1155 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001156
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001157 AnnotatedToken *Tok = &(I + 1)->First;
1158 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1159 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jaspereef30492013-02-11 12:36:37 +00001160 Tok->SpacesRequiredBefore = 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001161 join(Line, *(I + 1));
1162 I += 1;
1163 } else {
1164 // Check that we still have three lines and they fit into the limit.
1165 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1166 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001167 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001168
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001169 // Second, check that the next line does not contain any braces - if it
1170 // does, readability declines when putting it into a single line.
1171 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1172 return;
1173 do {
1174 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1175 return;
1176 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1177 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001178
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001179 // Last, check that the third line contains a single closing brace.
1180 Tok = &(I + 2)->First;
1181 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1182 Tok->MustBreakBefore)
1183 return;
1184
1185 join(Line, *(I + 1));
1186 join(Line, *(I + 2));
1187 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001188 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001189 }
1190
1191 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1192 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001193 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1194 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001195 }
1196
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001197 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1198 A.Last->Children.push_back(B.First);
1199 while (!A.Last->Children.empty()) {
1200 A.Last->Children[0].Parent = A.Last;
1201 A.Last = &A.Last->Children[0];
1202 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001203 }
1204
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001205 bool touchesRanges(const AnnotatedLine &TheLine) {
1206 const FormatToken *First = &TheLine.First.FormatTok;
1207 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001208 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001209 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001210 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001211 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1212 Ranges[i].getBegin()) &&
1213 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1214 LineRange.getBegin()))
1215 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001216 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001217 return false;
1218 }
1219
1220 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001221 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001222 }
1223
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001224 /// \brief Add a new line and the required indent before the first Token
1225 /// of the \c UnwrappedLine if there was no structural parsing error.
1226 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001227 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1228 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001229 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001230
Daniel Jasperbbc84152013-01-29 11:27:30 +00001231 unsigned Newlines =
1232 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001233 if (Newlines == 0 && !Tok.IsFirst)
1234 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001235
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001236 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001237 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001238 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001239 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1240 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001241 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001242 }
1243
Alexander Kornienko116ba682013-01-14 11:34:14 +00001244 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245 FormatStyle Style;
1246 Lexer &Lex;
1247 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001248 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001249 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001250 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001251 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001252};
1253
Daniel Jasperbbc84152013-01-29 11:27:30 +00001254tooling::Replacements
1255reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1256 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001257 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001258 OwningPtr<DiagnosticConsumer> DiagPrinter;
1259 if (DiagClient == 0) {
1260 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1261 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1262 DiagClient = DiagPrinter.get();
1263 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001264 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001265 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001266 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001267 Diagnostics.setSourceManager(&SourceMgr);
1268 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001269 return formatter.format();
1270}
1271
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001272LangOptions getFormattingLangOpts() {
1273 LangOptions LangOpts;
1274 LangOpts.CPlusPlus = 1;
1275 LangOpts.CPlusPlus11 = 1;
1276 LangOpts.Bool = 1;
1277 LangOpts.ObjC1 = 1;
1278 LangOpts.ObjC2 = 1;
1279 return LangOpts;
1280}
1281
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001282} // namespace format
1283} // namespace clang