blob: f03b77853ce97e35324acc41d24854fac94975c1 [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 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 Jaspere9de2602012-12-06 09:56:08 +0000307 /// \brief The position the first "<<" operator encountered on each level.
308 ///
309 /// Used to align "<<" operators. 0 if no such operator has been encountered
310 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000311 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000312
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000313 /// \brief Whether a newline needs to be inserted before the block's closing
314 /// brace.
315 ///
316 /// We only want to insert a newline before the closing brace if there also
317 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000318 bool BreakBeforeClosingBrace;
319
Daniel Jasperca6623b2013-01-28 12:45:14 +0000320 /// \brief The column of a \c ? in a conditional expression;
321 unsigned QuestionColumn;
322
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000323 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
324 /// lines, in this context.
325 bool AvoidBinPacking;
326
327 /// \brief Break after the next comma (or all the commas in this context if
328 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000329 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000330
331 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000332 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000333
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000334 /// \brief The position of the colon in an ObjC method declaration/call.
335 unsigned ColonPos;
336
Daniel Jasper337816e2013-01-11 10:22:12 +0000337 bool operator<(const ParenState &Other) const {
338 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000339 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000340 if (LastSpace != Other.LastSpace)
341 return LastSpace < Other.LastSpace;
342 if (FirstLessLess != Other.FirstLessLess)
343 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000344 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
345 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000346 if (QuestionColumn != Other.QuestionColumn)
347 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000348 if (AvoidBinPacking != Other.AvoidBinPacking)
349 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000350 if (BreakBeforeParameter != Other.BreakBeforeParameter)
351 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000352 if (HasMultiParameterLine != Other.HasMultiParameterLine)
353 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000354 if (ColonPos != Other.ColonPos)
355 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000356 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000357 }
358 };
359
360 /// \brief The current state when indenting a unwrapped line.
361 ///
362 /// As the indenting tries different combinations this is copied by value.
363 struct LineState {
364 /// \brief The number of used columns in the current line.
365 unsigned Column;
366
367 /// \brief The token that needs to be next formatted.
368 const AnnotatedToken *NextToken;
369
Daniel Jasperbbc84152013-01-29 11:27:30 +0000370 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000371 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000372 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000373 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000374
375 /// \brief \c true if this line contains a continued for-loop section.
376 bool LineContainsContinuedForLoopSection;
377
Daniel Jasper400adc62013-02-08 15:28:42 +0000378 /// \brief The level of nesting inside (), [], <> and {}.
379 unsigned ParenLevel;
380
Daniel Jasper337816e2013-01-11 10:22:12 +0000381 /// \brief A stack keeping track of properties applying to parenthesis
382 /// levels.
383 std::vector<ParenState> Stack;
384
385 /// \brief Comparison operator to be able to used \c LineState in \c map.
386 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000387 if (Other.NextToken != NextToken)
388 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000389 if (Other.Column != Column)
390 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000391 if (Other.VariablePos != VariablePos)
392 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000393 if (Other.LineContainsContinuedForLoopSection !=
394 LineContainsContinuedForLoopSection)
395 return LineContainsContinuedForLoopSection;
Daniel Jasper400adc62013-02-08 15:28:42 +0000396 if (Other.ParenLevel != ParenLevel)
397 return Other.ParenLevel < ParenLevel;
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());
Daniel Jasperf7935112012-12-03 18:12:45 +0000414
Daniel Jasper4b866272013-02-01 11:00:45 +0000415 if (Current.Type == TT_ImplicitStringLiteral) {
416 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
417 State.NextToken->FormatTok.TokenLength;
418 if (State.NextToken->Children.empty())
419 State.NextToken = NULL;
420 else
421 State.NextToken = &State.NextToken->Children[0];
422 return;
423 }
424
Daniel Jasperf7935112012-12-03 18:12:45 +0000425 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000426 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000427 if (Current.is(tok::r_brace)) {
428 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000429 } else if (Current.is(tok::string_literal) &&
430 Previous.is(tok::string_literal)) {
431 State.Column = State.Column - Previous.FormatTok.TokenLength;
432 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000433 State.Stack.back().FirstLessLess != 0) {
434 State.Column = State.Stack.back().FirstLessLess;
435 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000436 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000437 Current.is(tok::period) || Current.is(tok::arrow) ||
438 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000439 // Indent and extra 4 spaces after if we know the current expression is
440 // continued. Don't do that on the top level, as we already indent 4
441 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000442 State.Column = std::max(State.Stack.back().LastSpace,
443 State.Stack.back().Indent) + 4;
444 } else if (Current.Type == TT_ConditionalExpr) {
445 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000446 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000447 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
448 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000449 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000450 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
451 Current.Type == TT_StartOfName) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000452 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000453 } else if (Current.Type == TT_ObjCSelectorName) {
454 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
455 State.Column =
456 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
457 } else {
458 State.Column = State.Stack.back().Indent;
459 State.Stack.back().ColonPos =
460 State.Column + Current.FormatTok.TokenLength;
461 }
462 } else if (Previous.Type == TT_ObjCMethodExpr) {
463 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000464 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000465 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000466 }
467
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000468 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000469 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000470
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000471 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000472 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000473
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000474 if (!DryRun) {
475 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000476 Whitespaces.replaceWhitespace(Current, 1, State.Column,
477 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000478 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000479 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
480 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000481 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000482
Daniel Jasper400adc62013-02-08 15:28:42 +0000483 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000484 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000485 State.Stack.back().Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000486 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000487 if (Current.is(tok::equal) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000488 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000489 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000490
Daniel Jaspereef30492013-02-11 12:36:37 +0000491 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000492
Daniel Jasperf7935112012-12-03 18:12:45 +0000493 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000494 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000495
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000496 if (Current.Type == TT_ObjCSelectorName &&
497 State.Stack.back().ColonPos == 0) {
498 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
499 State.Column + Spaces + Current.FormatTok.TokenLength)
500 State.Stack.back().ColonPos =
501 State.Stack.back().Indent + Current.LongestObjCSelectorName;
502 else
503 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000504 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000505 }
506
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000507 if (Current.Type != TT_LineComment &&
508 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
509 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000510 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000511 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000512 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000513
Daniel Jaspere9de2602012-12-06 09:56:08 +0000514 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000515 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
516 // Treat the condition inside an if as if it was a second function
517 // parameter, i.e. let nested calls have an indent of 4.
518 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000519 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000520 // Top-level spaces are exempt as that mostly leads to better results.
521 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000522 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000523 Previous.Type == TT_ConditionalExpr ||
524 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000525 getPrecedence(Previous) != prec::Assignment)
526 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000527 else if (Previous.Type == TT_InheritanceColon)
528 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000529 else if (Previous.ParameterCount > 1 &&
530 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000531 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000532 Previous.Type == TT_TemplateOpener))
533 // If this function has multiple parameters, indent nested calls from
534 // the start of the first parameter.
535 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000536 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000537
538 // If we break after an {, we should also break before the corresponding }.
539 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000541
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000542 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000543 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000544 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000545 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000546 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
547 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000548 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
549 Line.MustBeDeclaration))
Daniel Jasperacc33662013-02-08 08:22:00 +0000550 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000551
Daniel Jaspere941b162013-01-23 10:08:28 +0000552 // Any break on this level means that the parent level has been broken
553 // and we need to avoid bin packing there.
554 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000555 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperacc33662013-02-08 08:22:00 +0000556 State.Stack[i].BreakBeforeParameter = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000557 }
558 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000559
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000560 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000561 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000562
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000563 /// \brief Mark the next token as consumed in \p State and modify its stacks
564 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000565 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000566 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000567 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000568
Daniel Jaspereead02b2013-02-14 08:42:54 +0000569 if (Current.Type == TT_InheritanceColon)
570 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000571 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
572 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000573 if (Current.is(tok::question))
574 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000575 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000576 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000577 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
578 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000579 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000580
Daniel Jasper400adc62013-02-08 15:28:42 +0000581 // Insert scopes created by fake parenthesis.
582 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
583 ParenState NewParenState = State.Stack.back();
584 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
585 State.Stack.push_back(NewParenState);
586 }
587
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000588 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
591 Current.is(tok::l_brace) ||
592 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000593 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000594 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000595 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000596 NewIndent = 2 + State.Stack.back().LastSpace;
597 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000598 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000599 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000600 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000601 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000602 State.Stack.push_back(
603 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
604 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000605 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000606 }
607
Daniel Jasperacc33662013-02-08 08:22:00 +0000608 // If this '[' opens an ObjC call, determine whether all parameters fit into
609 // one line and put one per line if they don't.
610 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
611 Current.MatchingParen != NULL) {
612 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
613 State.Stack.back().BreakBeforeParameter = true;
614 }
615
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000616 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000617 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000618 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
619 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
620 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000621 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000622 --State.ParenLevel;
623 }
624
625 // Remove scopes created by fake parenthesis.
626 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
627 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000629
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000630 if (State.NextToken->Children.empty())
631 State.NextToken = NULL;
632 else
633 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000634
635 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 }
637
Daniel Jasper2df93312013-01-09 10:16:05 +0000638 unsigned getColumnLimit() {
639 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
640 }
641
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000642 /// \brief An edge in the solution space from \c Previous->State to \c State,
643 /// inserting a newline dependent on the \c NewLine.
644 struct StateNode {
645 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
646 : State(State), NewLine(NewLine), Previous(Previous) {
647 }
648 LineState State;
649 bool NewLine;
650 StateNode *Previous;
651 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000652
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000653 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
654 ///
655 /// In case of equal penalties, we want to prefer states that were inserted
656 /// first. During state generation we make sure that we insert states first
657 /// that break the line as late as possible.
658 typedef std::pair<unsigned, unsigned> OrderedPenalty;
659
660 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
661 /// \c State has the given \c OrderedPenalty.
662 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
663
664 /// \brief The BFS queue type.
665 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
666 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000667
668 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000670 /// This implements a variant of Dijkstra's algorithm on the graph that spans
671 /// the solution space (\c LineStates are the nodes). The algorithm tries to
672 /// find the shortest path (the one with lowest penalty) from \p InitialState
673 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000674 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000675 std::set<LineState> Seen;
676
Daniel Jasper4b866272013-02-01 11:00:45 +0000677 // Insert start element into queue.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000678 StateNode *Node=
679 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
680 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
681 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000682
683 // While not empty, take first element and follow edges.
684 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000685 unsigned Penalty = Queue.top().first.first;
686 StateNode *Node= Queue.top().second;
687 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000688 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000689 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000690 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000691 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000692
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000693 if (!Seen.insert(Node->State).second)
694 // State already examined with lower penalty.
695 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000696
Manuel Klimekaf491072013-02-13 10:54:19 +0000697 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
698 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000699 }
700
701 if (Queue.empty())
702 // We were unable to find a solution, do nothing.
703 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000704 return 0;
705
Daniel Jasper4b866272013-02-01 11:00:45 +0000706 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000707 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000708 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000709
Daniel Jasper4b866272013-02-01 11:00:45 +0000710 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000711 return Queue.top().second->State.Column;
712 }
713
714 void reconstructPath(LineState &State, StateNode *Current) {
715 // FIXME: This recursive implementation limits the possible number
716 // of tokens per line if compiled into a binary with small stack space.
717 // To become more independent of stack frame limitations we would need
718 // to also change the TokenAnnotator.
719 if (Current->Previous == NULL)
720 return;
721 reconstructPath(State, Current->Previous);
722 DEBUG({
723 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000724 llvm::errs()
725 << "Penalty for splitting before "
726 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
727 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000728 }
729 });
730 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000731 }
732
Manuel Klimekaf491072013-02-13 10:54:19 +0000733 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000734 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000735 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000736 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000737 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
738 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000739 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000740 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000741 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000742 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000743 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000744 Penalty += PreviousNode->State.NextToken->SplitPenalty;
745
746 StateNode *Node = new (Allocator.Allocate())
747 StateNode(PreviousNode->State, NewLine, PreviousNode);
748 addTokenToState(NewLine, true, Node->State);
749 if (Node->State.Column > getColumnLimit()) {
750 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000751 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000752 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000753
754 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
755 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000756 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000757
Daniel Jasper4b866272013-02-01 11:00:45 +0000758 /// \brief Returns \c true, if a line break after \p State is allowed.
759 bool canBreak(const LineState &State) {
760 if (!State.NextToken->CanBreakBefore &&
761 !(State.NextToken->is(tok::r_brace) &&
762 State.Stack.back().BreakBeforeClosingBrace))
763 return false;
764 // Trying to insert a parameter on a new line if there are already more than
765 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000766 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000767 State.Stack.back().AvoidBinPacking)
768 return false;
769 return true;
770 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000771
Daniel Jasper4b866272013-02-01 11:00:45 +0000772 /// \brief Returns \c true, if a line break after \p State is mandatory.
773 bool mustBreak(const LineState &State) {
774 if (State.NextToken->MustBreakBefore)
775 return true;
776 if (State.NextToken->is(tok::r_brace) &&
777 State.Stack.back().BreakBeforeClosingBrace)
778 return true;
779 if (State.NextToken->Parent->is(tok::semi) &&
780 State.LineContainsContinuedForLoopSection)
781 return true;
782 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000783 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000784 !isTrailingComment(*State.NextToken) &&
785 State.NextToken->isNot(tok::r_paren))
Daniel Jasper4b866272013-02-01 11:00:45 +0000786 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000787 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
788 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000789 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000790 State.NextToken->LongestObjCSelectorName == 0 &&
791 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000792 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000793 if ((State.NextToken->Type == TT_CtorInitializerColon ||
794 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000795 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000796 return true;
797 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000798 }
799
Daniel Jasperf7935112012-12-03 18:12:45 +0000800 FormatStyle Style;
801 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000802 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000803 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000804 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000805 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000806
807 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
808 QueueType Queue;
809 // Increasing count of \c StateNode items we have created. This is used
810 // to create a deterministic order independent of the container.
811 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000812};
813
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000814class LexerBasedFormatTokenSource : public FormatTokenSource {
815public:
816 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000817 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000818 IdentTable(Lex.getLangOpts()) {
819 Lex.SetKeepWhitespaceMode(true);
820 }
821
822 virtual FormatToken getNextToken() {
823 if (GreaterStashed) {
824 FormatTok.NewlinesBefore = 0;
825 FormatTok.WhiteSpaceStart =
826 FormatTok.Tok.getLocation().getLocWithOffset(1);
827 FormatTok.WhiteSpaceLength = 0;
828 GreaterStashed = false;
829 return FormatTok;
830 }
831
832 FormatTok = FormatToken();
833 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000834 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000835 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000836 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
837 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000838
839 // Consume and record whitespace until we find a significant token.
840 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000841 unsigned Newlines = Text.count('\n');
842 unsigned EscapedNewlines = Text.count("\\\n");
843 FormatTok.NewlinesBefore += Newlines;
844 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000845 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
846
847 if (FormatTok.Tok.is(tok::eof))
848 return FormatTok;
849 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000850 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000851 }
Manuel Klimekef920692013-01-07 07:56:50 +0000852
853 // Now FormatTok is the next non-whitespace token.
854 FormatTok.TokenLength = Text.size();
855
Manuel Klimek1abf7892013-01-04 23:34:14 +0000856 // In case the token starts with escaped newlines, we want to
857 // take them into account as whitespace - this pattern is quite frequent
858 // in macro definitions.
859 // FIXME: What do we want to do with other escaped spaces, and escaped
860 // spaces or newlines in the middle of tokens?
861 // FIXME: Add a more explicit test.
862 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000863 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000864 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000865 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000866 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000867 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000868 }
869
870 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000871 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000872 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000873 FormatTok.Tok.setKind(Info.getTokenID());
874 }
875
876 if (FormatTok.Tok.is(tok::greatergreater)) {
877 FormatTok.Tok.setKind(tok::greater);
878 GreaterStashed = true;
879 }
880
881 return FormatTok;
882 }
883
Nico Weber29f9dea2013-02-11 15:32:15 +0000884 IdentifierTable &getIdentTable() { return IdentTable; }
885
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000886private:
887 FormatToken FormatTok;
888 bool GreaterStashed;
889 Lexer &Lex;
890 SourceManager &SourceMgr;
891 IdentifierTable IdentTable;
892
893 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000894 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000895 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
896 Tok.getLength());
897 }
898};
899
Daniel Jasperf7935112012-12-03 18:12:45 +0000900class Formatter : public UnwrappedLineConsumer {
901public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000902 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
903 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000904 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000905 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000906 Whitespaces(SourceMgr), Ranges(Ranges) {
907 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000908
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000909 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000910
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000911 void deriveLocalStyle() {
912 unsigned CountBoundToVariable = 0;
913 unsigned CountBoundToType = 0;
914 bool HasCpp03IncompatibleFormat = false;
915 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
916 if (AnnotatedLines[i].First.Children.empty())
917 continue;
918 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
919 while (!Tok->Children.empty()) {
920 if (Tok->Type == TT_PointerOrReference) {
921 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
922 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
923 if (SpacesBefore && !SpacesAfter)
924 ++CountBoundToVariable;
925 else if (!SpacesBefore && SpacesAfter)
926 ++CountBoundToType;
927 }
928
Daniel Jasper400adc62013-02-08 15:28:42 +0000929 if (Tok->Type == TT_TemplateCloser &&
930 Tok->Parent->Type == TT_TemplateCloser &&
931 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000932 HasCpp03IncompatibleFormat = true;
933 Tok = &Tok->Children[0];
934 }
935 }
936 if (Style.DerivePointerBinding) {
937 if (CountBoundToType > CountBoundToVariable)
938 Style.PointerBindsToType = true;
939 else if (CountBoundToType < CountBoundToVariable)
940 Style.PointerBindsToType = false;
941 }
942 if (Style.Standard == FormatStyle::LS_Auto) {
943 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
944 : FormatStyle::LS_Cpp03;
945 }
946 }
947
Daniel Jasperf7935112012-12-03 18:12:45 +0000948 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000949 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000950 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000951 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000952 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +0000953 TokenAnnotator Annotator(Style, SourceMgr, Lex,
954 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000955 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +0000956 Annotator.annotate(AnnotatedLines[i]);
957 }
958 deriveLocalStyle();
959 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
960 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000961 }
Manuel Klimekb95f5452013-02-08 17:38:27 +0000962 std::vector<int> IndentForLevel;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000963 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
964 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000965 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000966 const AnnotatedLine &TheLine = *I;
Manuel Klimekb95f5452013-02-08 17:38:27 +0000967 int Offset = GetIndentOffset(TheLine.First);
968 while (IndentForLevel.size() <= TheLine.Level)
969 IndentForLevel.push_back(-1);
970 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000971 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Manuel Klimekb95f5452013-02-08 17:38:27 +0000972 unsigned LevelIndent = GetIndent(IndentForLevel, TheLine.Level);
973 unsigned Indent = LevelIndent;
974 if (static_cast<int>(Indent) + Offset >= 0)
975 Indent += Offset;
976 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
977 StructuralError) {
978 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
979 TheLine.First.FormatTok.Tok.getLocation()) - 1;
980 } else {
981 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
982 PreviousEndOfLineColumn);
983 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000984 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000985 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000986 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000987 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000988 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +0000989 IndentForLevel[TheLine.Level] = LevelIndent;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000990 } else {
991 // If we did not reformat this unwrapped line, the column at the end of
992 // the last token is unchanged - thus, we can calculate the end of the
Manuel Klimekb95f5452013-02-08 17:38:27 +0000993 // last token.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +0000994 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000995 SourceMgr.getSpellingColumnNumber(
996 TheLine.Last->FormatTok.Tok.getLocation()) +
997 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000998 SourceMgr, Lex.getLangOpts()) - 1;
Daniel Jasper22045622013-02-12 16:51:23 +0000999 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1000 TheLine.First.FormatTok.IsFirst) {
1001 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1002 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1003 unsigned LevelIndent = Indent;
1004 if (static_cast<int>(LevelIndent) - Offset >= 0)
1005 LevelIndent -= Offset;
1006 IndentForLevel[TheLine.Level] = LevelIndent;
1007 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001008 }
1009 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001010 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001011 }
1012
1013private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001014 /// \brief Get the indent of \p Level from \p IndentForLevel.
1015 ///
1016 /// \p IndentForLevel must contain the indent for the level \c l
1017 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1018 /// that level is unknown.
1019 unsigned GetIndent(const std::vector<int> IndentForLevel,
1020 unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001021 if (IndentForLevel[Level] != -1)
1022 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001023 if (Level == 0)
1024 return 0;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001025 return GetIndent(IndentForLevel, Level - 1) + 2;
1026 }
1027
1028 /// \brief Get the offset of the line relatively to the level.
1029 ///
1030 /// For example, 'public:' labels in classes are offset by 1 or 2
1031 /// characters to the left from their level.
1032 int GetIndentOffset(const AnnotatedToken &RootToken) {
1033 bool IsAccessModifier = false;
1034 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1035 RootToken.is(tok::kw_private))
1036 IsAccessModifier = true;
1037 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1038 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1039 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1040 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1041 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1042 IsAccessModifier = true;
1043
1044 if (IsAccessModifier)
1045 return Style.AccessModifierOffset;
1046 return 0;
1047 }
1048
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001049 /// \brief Tries to merge lines into one.
1050 ///
1051 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1052 /// if possible; note that \c I will be incremented when lines are merged.
1053 ///
1054 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001055 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001056 std::vector<AnnotatedLine>::iterator &I,
1057 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001058 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1059
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001060 // We can never merge stuff if there are trailing line comments.
1061 if (I->Last->Type == TT_LineComment)
1062 return;
1063
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001064 // Check whether the UnwrappedLine can be put onto a single line. If
1065 // so, this is bound to be the optimal solution (by definition) and we
1066 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001067 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001068 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001069 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001070
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001071 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001072 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001073
Daniel Jasper25837aa2013-01-14 14:14:23 +00001074 if (I->Last->is(tok::l_brace)) {
1075 tryMergeSimpleBlock(I, E, Limit);
1076 } else if (I->First.is(tok::kw_if)) {
1077 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001078 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1079 I->First.FormatTok.IsFirst)) {
1080 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001081 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001082 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001083 }
1084
Daniel Jasper39825ea2013-01-14 15:40:57 +00001085 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1086 std::vector<AnnotatedLine>::iterator E,
1087 unsigned Limit) {
1088 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001089 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1090 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001091 if (I + 2 != E && (I + 2)->InPPDirective &&
1092 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1093 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001094 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001095 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001096 join(Line, *(++I));
1097 }
1098
Daniel Jasper25837aa2013-01-14 14:14:23 +00001099 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1100 std::vector<AnnotatedLine>::iterator E,
1101 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001102 if (!Style.AllowShortIfStatementsOnASingleLine)
1103 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001104 if ((I + 1)->InPPDirective != I->InPPDirective ||
1105 ((I + 1)->InPPDirective &&
1106 (I + 1)->First.FormatTok.HasUnescapedNewline))
1107 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001108 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001109 if (Line.Last->isNot(tok::r_paren))
1110 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001111 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001112 return;
1113 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1114 return;
1115 // Only inline simple if's (no nested if or else).
1116 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1117 return;
1118 join(Line, *(++I));
1119 }
1120
1121 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001122 std::vector<AnnotatedLine>::iterator E,
1123 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001124 // First, check that the current line allows merging. This is the case if
1125 // we're not in a control flow statement and the last token is an opening
1126 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001127 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001128 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001129 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1130 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1131 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1132 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001133 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001134 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1135 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001136 if (!AllowedTokens)
1137 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001138
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001139 AnnotatedToken *Tok = &(I + 1)->First;
1140 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1141 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jaspereef30492013-02-11 12:36:37 +00001142 Tok->SpacesRequiredBefore = 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001143 join(Line, *(I + 1));
1144 I += 1;
1145 } else {
1146 // Check that we still have three lines and they fit into the limit.
1147 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1148 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001149 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001150
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001151 // Second, check that the next line does not contain any braces - if it
1152 // does, readability declines when putting it into a single line.
1153 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1154 return;
1155 do {
1156 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1157 return;
1158 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1159 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001160
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001161 // Last, check that the third line contains a single closing brace.
1162 Tok = &(I + 2)->First;
1163 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1164 Tok->MustBreakBefore)
1165 return;
1166
1167 join(Line, *(I + 1));
1168 join(Line, *(I + 2));
1169 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001170 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001171 }
1172
1173 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1174 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001175 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1176 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001177 }
1178
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001179 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1180 A.Last->Children.push_back(B.First);
1181 while (!A.Last->Children.empty()) {
1182 A.Last->Children[0].Parent = A.Last;
1183 A.Last = &A.Last->Children[0];
1184 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001185 }
1186
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001187 bool touchesRanges(const AnnotatedLine &TheLine) {
1188 const FormatToken *First = &TheLine.First.FormatTok;
1189 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001190 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001191 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001192 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001193 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1194 Ranges[i].getBegin()) &&
1195 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1196 LineRange.getBegin()))
1197 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001198 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001199 return false;
1200 }
1201
1202 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001203 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001204 }
1205
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001206 /// \brief Add a new line and the required indent before the first Token
1207 /// of the \c UnwrappedLine if there was no structural parsing error.
1208 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001209 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1210 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001211 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001212
Daniel Jasperbbc84152013-01-29 11:27:30 +00001213 unsigned Newlines =
1214 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001215 if (Newlines == 0 && !Tok.IsFirst)
1216 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001217
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001218 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001219 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001220 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001221 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1222 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001223 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001224 }
1225
Alexander Kornienko116ba682013-01-14 11:34:14 +00001226 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001227 FormatStyle Style;
1228 Lexer &Lex;
1229 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001230 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001231 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001232 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001233 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001234};
1235
Daniel Jasperbbc84152013-01-29 11:27:30 +00001236tooling::Replacements
1237reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1238 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001239 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001240 OwningPtr<DiagnosticConsumer> DiagPrinter;
1241 if (DiagClient == 0) {
1242 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1243 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1244 DiagClient = DiagPrinter.get();
1245 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001246 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001247 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001248 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001249 Diagnostics.setSourceManager(&SourceMgr);
1250 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001251 return formatter.format();
1252}
1253
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001254LangOptions getFormattingLangOpts() {
1255 LangOptions LangOpts;
1256 LangOpts.CPlusPlus = 1;
1257 LangOpts.CPlusPlus11 = 1;
1258 LangOpts.Bool = 1;
1259 LangOpts.ObjC1 = 1;
1260 LangOpts.ObjC2 = 1;
1261 return LangOpts;
1262}
1263
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001264} // namespace format
1265} // namespace clang