blob: 40e980f67da01fff9736852406e8bfec0717beb6 [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 Jasper2cf17bf2013-02-27 09:47:53 +000064 GoogleStyle.BinPackParameters = true;
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 Jasper2cf17bf2013-02-27 09:47:53 +000077 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper94f0e132013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperd1ae3582013-03-20 12:37:50 +000088static bool isComparison(const AnnotatedToken &Tok) {
89 prec::Level Precedence = getPrecedence(Tok);
90 return Tok.Type == TT_BinaryOperator &&
91 (Precedence == prec::Equality || Precedence == prec::Relational);
92}
93
Daniel Jasperacc33662013-02-08 08:22:00 +000094// Returns the length of everything up to the first possible line break after
95// the ), ], } or > matching \c Tok.
96static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
97 if (Tok.MatchingParen == NULL)
98 return 0;
99 AnnotatedToken *End = Tok.MatchingParen;
100 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
101 End = &End->Children[0];
102 }
103 return End->TotalLength - Tok.TotalLength + 1;
104}
105
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000106/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000107///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000108/// This includes special handling for certain constructs, e.g. the alignment of
109/// trailing line comments.
110class WhitespaceManager {
111public:
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000112 WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
113 : SourceMgr(SourceMgr), Style(Style) {}
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000114
115 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
116 /// each \c AnnotatedToken.
117 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000118 unsigned Spaces, unsigned WhitespaceStartColumn) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000119 // 2+ newlines mean an empty line separating logic scopes.
120 if (NewLines >= 2)
121 alignComments();
122
123 // Align line comments if they are trailing or if they continue other
124 // trailing comments.
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000125 if (isTrailingComment(Tok)) {
126 // Remove the comment's trailing whitespace.
127 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
128 Replaces.insert(tooling::Replacement(
129 SourceMgr, Tok.FormatTok.Tok.getLocation().getLocWithOffset(
130 Tok.FormatTok.TokenLength),
131 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
132
133 // Align comment with other comments.
134 if (Tok.Parent != NULL || !Comments.empty()) {
135 if (Style.ColumnLimit >=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000136 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000137 StoredComment Comment;
138 Comment.Tok = Tok.FormatTok;
139 Comment.Spaces = Spaces;
140 Comment.NewLines = NewLines;
141 Comment.MinColumn =
142 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
143 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
144 Comments.push_back(Comment);
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000145 return;
146 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000147 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000148 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000149
150 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000151 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000152 alignComments();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000153
154 if (Tok.Type == TT_BlockComment)
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000155 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000156
Manuel Klimek1998ea22013-02-20 10:15:13 +0000157 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000158 }
159
160 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
161 /// backslashes to escape newlines inside a preprocessor directive.
162 ///
163 /// This function and \c replaceWhitespace have the same behavior if
164 /// \c Newlines == 0.
165 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000166 unsigned Spaces, unsigned WhitespaceStartColumn) {
167 if (Tok.Type == TT_BlockComment)
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000168 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000169
170 storeReplacement(Tok.FormatTok,
171 getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000172 }
173
174 /// \brief Inserts a line break into the middle of a token.
175 ///
176 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
177 /// break and \p Postfix before the rest of the token starts in the next line.
178 ///
179 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
180 /// used to generate the correct line break.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000181 void breakToken(const FormatToken &Tok, unsigned Offset,
182 unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
183 bool InPPDirective, unsigned Spaces,
184 unsigned WhitespaceStartColumn) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000185 std::string NewLineText;
186 if (!InPPDirective)
187 NewLineText = getNewLineText(1, Spaces);
188 else
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000189 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000190 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000191 SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
192 Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
193 ReplacementText));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000194 }
195
196 /// \brief Returns all the \c Replacements created during formatting.
197 const tooling::Replacements &generateReplacements() {
198 alignComments();
199 return Replaces;
200 }
201
202private:
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000203 /// \brief Finds a common prefix of lines of a block comment to properly
204 /// indent (and possibly decorate with '*'s) added lines.
205 ///
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000206 /// The first line is ignored (it's special and starts with /*). The number of
207 /// lines should be more than one.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000208 static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
209 const char *PrefixChars = " *") {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000210 assert(Lines.size() > 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000211 StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
212 for (size_t i = 2; i < Lines.size(); ++i) {
213 for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
214 if (Prefix[j] != Lines[i][j]) {
215 Prefix = Prefix.substr(0, j);
216 break;
217 }
218 }
219 }
220 return Prefix;
221 }
222
223 void splitLineInComment(const FormatToken &Tok, StringRef Line,
224 size_t StartColumn, StringRef LinePrefix,
225 bool InPPDirective, bool CommentHasMoreLines,
226 const char *WhiteSpaceChars = " ") {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000227 size_t ColumnLimit = Style.ColumnLimit - (InPPDirective ? 2 : 0);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000228 const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000229 while (Line.rtrim().size() + StartColumn > ColumnLimit) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000230 // Try to break at the last whitespace before the column limit.
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000231 size_t SpacePos =
232 Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000233 if (SpacePos == StringRef::npos) {
234 // Try to find any whitespace in the line.
235 SpacePos = Line.find_first_of(WhiteSpaceChars);
236 if (SpacePos == StringRef::npos) // No whitespace found, give up.
237 break;
238 }
239
240 StringRef NextCut = Line.substr(0, SpacePos).rtrim();
241 StringRef RemainingLine = Line.substr(SpacePos).ltrim();
242 if (RemainingLine.empty())
243 break;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000244
245 if (RemainingLine == "*/" && LinePrefix.endswith("* "))
246 LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
247
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000248 Line = RemainingLine;
249
250 size_t ReplaceChars = Line.begin() - NextCut.end();
251 breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
252 InPPDirective, 0,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000253 NextCut.size() + StartColumn);
254 StartColumn = LinePrefix.size();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000255 }
256
257 StringRef TrimmedLine = Line.rtrim();
258 if (TrimmedLine != Line || (InPPDirective && CommentHasMoreLines)) {
259 // Remove trailing whitespace/insert backslash.
260 breakToken(Tok, TrimmedLine.end() - TokenStart,
261 Line.size() - TrimmedLine.size() + 1, "", "", InPPDirective, 0,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000262 TrimmedLine.size() + StartColumn);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000263 }
264 }
265
266 void indentBlockComment(const AnnotatedToken &Tok, int Indent,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000267 int WhitespaceStartColumn, int NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000268 bool InPPDirective) {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000269 int StartColumn = NewLines > 0 ? Indent : WhitespaceStartColumn + Indent;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000270 const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
271 const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
272 const int IndentDelta = Indent - CurrentIndent;
273 const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
274 Tok.FormatTok.TokenLength);
275 assert(Text.startswith("/*") && Text.endswith("*/"));
276
277 SmallVector<StringRef, 16> Lines;
278 Text.split(Lines, "\n");
279
280 if (IndentDelta > 0) {
281 std::string WhiteSpace(IndentDelta, ' ');
282 for (size_t i = 1; i < Lines.size(); ++i) {
283 Replaces.insert(tooling::Replacement(
284 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
285 0, WhiteSpace));
286 }
287 } else if (IndentDelta < 0) {
288 std::string WhiteSpace(-IndentDelta, ' ');
289 // Check that the line is indented enough.
290 for (size_t i = 1; i < Lines.size(); ++i) {
291 if (!Lines[i].startswith(WhiteSpace))
292 return;
293 }
294 for (size_t i = 1; i < Lines.size(); ++i) {
295 Replaces.insert(tooling::Replacement(
296 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
297 -IndentDelta, ""));
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000298 }
299 }
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000300
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000301 // Split long lines in comments.
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000302 size_t PrefixSize = 0;
303 std::string NewPrefix;
304 if (Lines.size() > 1) {
305 StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
306 PrefixSize = CurrentPrefix.size();
307 NewPrefix = (IndentDelta < 0)
308 ? CurrentPrefix.substr(-IndentDelta).str()
309 : std::string(IndentDelta, ' ') + CurrentPrefix.str();
310 if (CurrentPrefix.endswith("*")) {
311 NewPrefix += " ";
312 ++PrefixSize;
313 }
314 } else if (Tok.Parent == 0) {
315 NewPrefix = std::string(StartColumn, ' ') + " * ";
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000316 }
317
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000318 StartColumn += 2;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000319 for (size_t i = 0; i < Lines.size(); ++i) {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000320 StringRef Line = Lines[i].substr(i == 0 ? 2 : PrefixSize);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000321 splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
322 InPPDirective, i != Lines.size() - 1);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000323 StartColumn = NewPrefix.size();
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000324 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000325 }
326
Manuel Klimek1998ea22013-02-20 10:15:13 +0000327 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
328 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
329 }
330
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000331 std::string getNewLineText(unsigned NewLines, unsigned Spaces,
332 unsigned WhitespaceStartColumn) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000333 std::string NewLineText;
334 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000335 unsigned Offset =
336 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000337 for (unsigned i = 0; i < NewLines; ++i) {
338 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
339 NewLineText += "\\\n";
340 Offset = 0;
341 }
342 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000343 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000344 }
345
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000346 /// \brief Structure to store a comment for later layout and alignment.
347 struct StoredComment {
348 FormatToken Tok;
349 unsigned MinColumn;
350 unsigned MaxColumn;
351 unsigned NewLines;
352 unsigned Spaces;
353 };
354 SmallVector<StoredComment, 16> Comments;
355 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
356
357 /// \brief Try to align all stashed comments.
358 void alignComments() {
359 unsigned MinColumn = 0;
360 unsigned MaxColumn = UINT_MAX;
361 comment_iterator Start = Comments.begin();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000362 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000363 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
364 alignComments(Start, I, MinColumn);
365 MinColumn = I->MinColumn;
366 MaxColumn = I->MaxColumn;
367 Start = I;
368 } else {
369 MinColumn = std::max(MinColumn, I->MinColumn);
370 MaxColumn = std::min(MaxColumn, I->MaxColumn);
371 }
372 }
373 alignComments(Start, Comments.end(), MinColumn);
374 Comments.clear();
375 }
376
377 /// \brief Put all the comments between \p I and \p E into \p Column.
378 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
379 while (I != E) {
380 unsigned Spaces = I->Spaces + Column - I->MinColumn;
Daniel Jasperaab220f2013-03-20 13:53:11 +0000381 storeReplacement(
382 I->Tok, std::string(I->NewLines, '\n') + std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000383 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000384 }
385 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000386
387 /// \brief Stores \p Text as the replacement for the whitespace in front of
388 /// \p Tok.
389 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000390 // Don't create a replacement, if it does not change anything.
391 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
392 Tok.WhiteSpaceLength) == Text)
393 return;
394
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000395 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
396 Tok.WhiteSpaceLength, Text));
397 }
398
399 SourceManager &SourceMgr;
400 tooling::Replacements Replaces;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000401 const FormatStyle &Style;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000402};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000403
Daniel Jasperf7935112012-12-03 18:12:45 +0000404class UnwrappedLineFormatter {
405public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000406 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000407 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000408 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000409 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000410 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000411 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000412 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000413
Manuel Klimek1abf7892013-01-04 23:34:14 +0000414 /// \brief Formats an \c UnwrappedLine.
415 ///
416 /// \returns The column after the last token in the last line of the
417 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000418 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000419 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000420 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000421 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000422 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000423 State.Stack.push_back(
424 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
425 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000426 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000427 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000428 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000429 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000430 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000431
Manuel Klimek24998102013-01-16 14:55:28 +0000432 DEBUG({
433 DebugTokenState(*State.NextToken);
434 });
435
Daniel Jaspere9de2602012-12-06 09:56:08 +0000436 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000437 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000438
Daniel Jasper4b866272013-02-01 11:00:45 +0000439 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000440 unsigned ColumnLimit = Style.ColumnLimit;
441 if (NextLine && NextLine->InPPDirective &&
442 !NextLine->First.FormatTok.HasUnescapedNewline)
443 ColumnLimit = getColumnLimit();
444 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000445 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000446 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000447 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000448 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000449 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000450
Daniel Jasperacc33662013-02-08 08:22:00 +0000451 // If the ObjC method declaration does not fit on a line, we should format
452 // it with one arg per line.
453 if (Line.Type == LT_ObjCMethodDecl)
454 State.Stack.back().BreakBeforeParameter = true;
455
Daniel Jasper4b866272013-02-01 11:00:45 +0000456 // Find best solution in solution space.
457 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000458 }
459
460private:
Manuel Klimek24998102013-01-16 14:55:28 +0000461 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
462 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000463 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
464 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000465 llvm::errs();
466 }
467
Daniel Jasper337816e2013-01-11 10:22:12 +0000468 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000469 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
470 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000471 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
472 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000473 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000474 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
475 StartOfFunctionCall(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000476
Daniel Jasperf7935112012-12-03 18:12:45 +0000477 /// \brief The position to which a specific parenthesis level needs to be
478 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000479 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000480
Daniel Jaspere9de2602012-12-06 09:56:08 +0000481 /// \brief The position of the last space on each level.
482 ///
483 /// Used e.g. to break like:
484 /// functionCall(Parameter, otherCall(
485 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000486 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000487
Daniel Jaspere9de2602012-12-06 09:56:08 +0000488 /// \brief The position the first "<<" operator encountered on each level.
489 ///
490 /// Used to align "<<" operators. 0 if no such operator has been encountered
491 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000492 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000493
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000494 /// \brief Whether a newline needs to be inserted before the block's closing
495 /// brace.
496 ///
497 /// We only want to insert a newline before the closing brace if there also
498 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000499 bool BreakBeforeClosingBrace;
500
Daniel Jasperca6623b2013-01-28 12:45:14 +0000501 /// \brief The column of a \c ? in a conditional expression;
502 unsigned QuestionColumn;
503
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000504 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
505 /// lines, in this context.
506 bool AvoidBinPacking;
507
508 /// \brief Break after the next comma (or all the commas in this context if
509 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000510 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000511
512 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000513 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000514
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000515 /// \brief The position of the colon in an ObjC method declaration/call.
516 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000517
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000518 /// \brief The start of the most recent function in a builder-type call.
519 unsigned StartOfFunctionCall;
520
Daniel Jasper337816e2013-01-11 10:22:12 +0000521 bool operator<(const ParenState &Other) const {
522 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000523 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000524 if (LastSpace != Other.LastSpace)
525 return LastSpace < Other.LastSpace;
526 if (FirstLessLess != Other.FirstLessLess)
527 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000528 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
529 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000530 if (QuestionColumn != Other.QuestionColumn)
531 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000532 if (AvoidBinPacking != Other.AvoidBinPacking)
533 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000534 if (BreakBeforeParameter != Other.BreakBeforeParameter)
535 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000536 if (HasMultiParameterLine != Other.HasMultiParameterLine)
537 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000538 if (ColonPos != Other.ColonPos)
539 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000540 if (StartOfFunctionCall != Other.StartOfFunctionCall)
541 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000542 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 }
544 };
545
546 /// \brief The current state when indenting a unwrapped line.
547 ///
548 /// As the indenting tries different combinations this is copied by value.
549 struct LineState {
550 /// \brief The number of used columns in the current line.
551 unsigned Column;
552
553 /// \brief The token that needs to be next formatted.
554 const AnnotatedToken *NextToken;
555
Daniel Jasperbbc84152013-01-29 11:27:30 +0000556 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000557 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000558 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000559 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000560
561 /// \brief \c true if this line contains a continued for-loop section.
562 bool LineContainsContinuedForLoopSection;
563
Daniel Jasper400adc62013-02-08 15:28:42 +0000564 /// \brief The level of nesting inside (), [], <> and {}.
565 unsigned ParenLevel;
566
Daniel Jasper40c36c52013-02-18 11:05:07 +0000567 /// \brief The \c ParenLevel at the start of this line.
568 unsigned StartOfLineLevel;
569
Manuel Klimek02f640a2013-02-20 15:25:48 +0000570 /// \brief The start column of the string literal, if we're in a string
571 /// literal sequence, 0 otherwise.
572 unsigned StartOfStringLiteral;
573
Daniel Jasper337816e2013-01-11 10:22:12 +0000574 /// \brief A stack keeping track of properties applying to parenthesis
575 /// levels.
576 std::vector<ParenState> Stack;
577
578 /// \brief Comparison operator to be able to used \c LineState in \c map.
579 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000580 if (NextToken != Other.NextToken)
581 return NextToken < Other.NextToken;
582 if (Column != Other.Column)
583 return Column < Other.Column;
584 if (VariablePos != Other.VariablePos)
585 return VariablePos < Other.VariablePos;
586 if (LineContainsContinuedForLoopSection !=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000587 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000588 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000589 if (ParenLevel != Other.ParenLevel)
590 return ParenLevel < Other.ParenLevel;
591 if (StartOfLineLevel != Other.StartOfLineLevel)
592 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000593 if (StartOfStringLiteral != Other.StartOfStringLiteral)
594 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000595 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 }
597 };
598
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599 /// \brief Appends the next token to \p State and updates information
600 /// necessary for indentation.
601 ///
602 /// Puts the token on the current line if \p Newline is \c true and adds a
603 /// line break and necessary indentation otherwise.
604 ///
605 /// If \p DryRun is \c false, also creates and stores the required
606 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000607 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000608 const AnnotatedToken &Current = *State.NextToken;
609 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610
Daniel Jasper291f9362013-03-20 15:58:10 +0000611 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000612 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
613 State.NextToken->FormatTok.TokenLength;
614 if (State.NextToken->Children.empty())
615 State.NextToken = NULL;
616 else
617 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000618 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000619 }
620
Daniel Jasperf7935112012-12-03 18:12:45 +0000621 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000622 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000623 if (Current.is(tok::r_brace)) {
624 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000625 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000626 State.StartOfStringLiteral != 0) {
627 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000628 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000629 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000630 State.Stack.back().FirstLessLess != 0) {
631 State.Column = State.Stack.back().FirstLessLess;
632 } else if (State.ParenLevel != 0 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000633 (Previous.isOneOf(tok::equal, tok::coloncolon) ||
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000634 Current.isOneOf(tok::period, tok::arrow, tok::question) ||
635 isComparison(Previous))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000636 // Indent and extra 4 spaces after if we know the current expression is
637 // continued. Don't do that on the top level, as we already indent 4
638 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000639 State.Column = std::max(State.Stack.back().LastSpace,
640 State.Stack.back().Indent) + 4;
641 } else if (Current.Type == TT_ConditionalExpr) {
642 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000643 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000644 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
645 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000646 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000647 } else if (Previous.ClosesTemplateDeclaration ||
648 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000649 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000650 } else if (Current.Type == TT_ObjCSelectorName) {
651 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
652 State.Column =
653 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
654 } else {
655 State.Column = State.Stack.back().Indent;
656 State.Stack.back().ColonPos =
657 State.Column + Current.FormatTok.TokenLength;
658 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000659 } else if (Previous.Type == TT_ObjCMethodExpr ||
660 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000661 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000662 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000663 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000664 }
665
Daniel Jasper54a86022013-02-15 11:07:25 +0000666 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000667 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000668 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000669 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000670 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000671
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000672 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000673 unsigned NewLines = 1;
674 if (Current.Type == TT_LineComment)
675 NewLines =
676 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
677 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000678 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000679 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000680 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000681 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000682 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000683 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000684 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000685
Daniel Jasper400adc62013-02-08 15:28:42 +0000686 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000687 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000688
689 // Any break on this level means that the parent level has been broken
690 // and we need to avoid bin packing there.
691 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
692 State.Stack[i].BreakBeforeParameter = true;
693 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000694 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000695 State.Stack.back().BreakBeforeParameter = true;
696
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000697 // If we break after {, we should also break before the corresponding }.
698 if (Previous.is(tok::l_brace))
699 State.Stack.back().BreakBeforeClosingBrace = true;
700
701 if (State.Stack.back().AvoidBinPacking) {
702 // If we are breaking after '(', '{', '<', this is not bin packing
703 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000704 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000705 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
706 Line.MustBeDeclaration))
707 State.Stack.back().BreakBeforeParameter = true;
708 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000709 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000710 // FIXME: Put VariablePos into ParenState and remove second part of if().
711 if (Current.is(tok::equal) &&
712 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000713 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000714
Daniel Jaspereef30492013-02-11 12:36:37 +0000715 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000716
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000718 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000719
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000720 if (Current.Type == TT_ObjCSelectorName &&
721 State.Stack.back().ColonPos == 0) {
722 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000723 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000724 State.Stack.back().ColonPos =
725 State.Stack.back().Indent + Current.LongestObjCSelectorName;
726 else
727 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000728 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000729 }
730
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000731 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000732 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000733 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000734 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000735 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000736 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000737
Daniel Jaspere9de2602012-12-06 09:56:08 +0000738 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000739 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
740 // Treat the condition inside an if as if it was a second function
741 // parameter, i.e. let nested calls have an indent of 4.
742 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000743 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000744 // Top-level spaces are exempt as that mostly leads to better results.
745 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000746 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000747 Previous.Type == TT_ConditionalExpr ||
748 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000749 getPrecedence(Previous) != prec::Assignment)
750 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000751 else if (Previous.Type == TT_InheritanceColon)
752 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000753 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000754 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000755 Previous.Type == TT_TemplateOpener))
756 // If this function has multiple parameters, indent nested calls from
757 // the start of the first parameter.
758 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000760
Manuel Klimek1998ea22013-02-20 10:15:13 +0000761 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000762 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000763
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000764 /// \brief Mark the next token as consumed in \p State and modify its stacks
765 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000766 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000767 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000768 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000769
Daniel Jaspereead02b2013-02-14 08:42:54 +0000770 if (Current.Type == TT_InheritanceColon)
771 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000772 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
773 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000774 if (Current.is(tok::question))
775 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000776 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000777 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
778 State.Stack.back().StartOfFunctionCall =
779 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000780 if (Current.Type == TT_CtorInitializerColon) {
781 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
782 State.Stack.back().AvoidBinPacking = true;
783 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000784 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000785
Daniel Jasper400adc62013-02-08 15:28:42 +0000786 // Insert scopes created by fake parenthesis.
787 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
788 ParenState NewParenState = State.Stack.back();
789 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000790 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000791 State.Stack.push_back(NewParenState);
792 }
793
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000794 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000795 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000796 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000797 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000798 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000799 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000800 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000801 NewIndent = 2 + State.Stack.back().LastSpace;
802 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000803 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000804 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
805 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000806 AvoidBinPacking =
807 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000808 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000809 State.Stack.push_back(
810 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
811 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000812 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000813 }
814
Daniel Jasperacc33662013-02-08 08:22:00 +0000815 // If this '[' opens an ObjC call, determine whether all parameters fit into
816 // one line and put one per line if they don't.
817 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
818 Current.MatchingParen != NULL) {
819 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
820 State.Stack.back().BreakBeforeParameter = true;
821 }
822
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000823 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000824 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000825 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000826 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
827 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000828 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000829 --State.ParenLevel;
830 }
831
832 // Remove scopes created by fake parenthesis.
833 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
834 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000835 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000836
Manuel Klimek0c915712013-02-20 15:32:58 +0000837 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000838 State.StartOfStringLiteral = State.Column;
839 } else if (Current.isNot(tok::comment)) {
840 State.StartOfStringLiteral = 0;
841 }
842
Manuel Klimek1998ea22013-02-20 10:15:13 +0000843 State.Column += Current.FormatTok.TokenLength;
844
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 if (State.NextToken->Children.empty())
846 State.NextToken = NULL;
847 else
848 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000849
Manuel Klimek1998ea22013-02-20 10:15:13 +0000850 return breakProtrudingToken(Current, State, DryRun);
851 }
852
853 /// \brief If the current token sticks out over the end of the line, break
854 /// it if possible.
855 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
856 bool DryRun) {
857 if (Current.isNot(tok::string_literal))
858 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000859 // Only break up default narrow strings.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000860 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
861 if (!LiteralData || *LiteralData != '"')
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000862 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000863
864 unsigned Penalty = 0;
865 unsigned TailOffset = 0;
866 unsigned TailLength = Current.FormatTok.TokenLength;
867 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
868 unsigned OffsetFromStart = 0;
869 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000870 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000871 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000872 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000873 StringRef::size_type SplitPoint = getSplitPoint(
874 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000875 if (SplitPoint == StringRef::npos)
876 break;
877 assert(SplitPoint != 0);
878 // +2, because 'Text' starts after the opening quotes, and does not
879 // include the closing quote we need to insert.
880 unsigned WhitespaceStartColumn =
881 StartColumn + OffsetFromStart + SplitPoint + 2;
882 State.Stack.back().LastSpace = StartColumn;
883 if (!DryRun) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000884 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
885 0, "\"", "\"", Line.InPPDirective, StartColumn,
886 WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000887 }
888 TailOffset += SplitPoint + 1;
889 TailLength -= SplitPoint + 1;
890 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000891 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000892 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
893 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000894 }
895 State.Column = StartColumn + TailLength;
896 return Penalty;
897 }
898
899 StringRef::size_type
900 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000901 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000902 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000903 return SpaceOffset;
904 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000905 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000906 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000907 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
908 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000909 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000910 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000911 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000912 }
913
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000914 StringRef::size_type
915 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
916 StringRef::size_type NextEscape = Text.find('\\');
917 while (NextEscape != StringRef::npos && NextEscape < Offset) {
918 StringRef::size_type SequenceLength =
919 getEscapeSequenceLength(Text.substr(NextEscape));
920 if (Offset < NextEscape + SequenceLength)
921 return NextEscape;
922 NextEscape = Text.find('\\', NextEscape + SequenceLength);
923 }
924 return Offset;
925 }
926
927 unsigned getEscapeSequenceLength(StringRef Text) {
928 assert(Text[0] == '\\');
929 if (Text.size() < 2)
930 return 1;
931
932 switch (Text[1]) {
933 case 'u':
934 return 6;
935 case 'U':
936 return 10;
937 case 'x':
938 return getHexLength(Text);
939 default:
940 if (Text[1] >= '0' && Text[1] <= '7')
941 return getOctalLength(Text);
942 return 2;
943 }
944 }
945
946 unsigned getHexLength(StringRef Text) {
947 unsigned I = 2; // Point after '\x'.
948 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
949 (Text[I] >= 'a' && Text[I] <= 'f') ||
950 (Text[I] >= 'A' && Text[I] <= 'F'))) {
951 ++I;
952 }
953 return I;
954 }
955
956 unsigned getOctalLength(StringRef Text) {
957 unsigned I = 1;
958 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
959 ++I;
960 }
961 return I;
962 }
963
Daniel Jasper2df93312013-01-09 10:16:05 +0000964 unsigned getColumnLimit() {
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000965 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000966 }
967
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000968 /// \brief An edge in the solution space from \c Previous->State to \c State,
969 /// inserting a newline dependent on the \c NewLine.
970 struct StateNode {
971 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000972 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000973 LineState State;
974 bool NewLine;
975 StateNode *Previous;
976 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000977
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000978 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
979 ///
980 /// In case of equal penalties, we want to prefer states that were inserted
981 /// first. During state generation we make sure that we insert states first
982 /// that break the line as late as possible.
983 typedef std::pair<unsigned, unsigned> OrderedPenalty;
984
985 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
986 /// \c State has the given \c OrderedPenalty.
987 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
988
989 /// \brief The BFS queue type.
990 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
991 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000992
993 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000995 /// This implements a variant of Dijkstra's algorithm on the graph that spans
996 /// the solution space (\c LineStates are the nodes). The algorithm tries to
997 /// find the shortest path (the one with lowest penalty) from \p InitialState
998 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000999 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001000 std::set<LineState> Seen;
1001
Daniel Jasper4b866272013-02-01 11:00:45 +00001002 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001003 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001004 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1005 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1006 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001007
1008 // While not empty, take first element and follow edges.
1009 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001010 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001011 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001012 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001013 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001014 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001015 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001016 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001017
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001018 if (!Seen.insert(Node->State).second)
1019 // State already examined with lower penalty.
1020 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001021
Manuel Klimekaf491072013-02-13 10:54:19 +00001022 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1023 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001024 }
1025
1026 if (Queue.empty())
1027 // We were unable to find a solution, do nothing.
1028 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 return 0;
1030
Daniel Jasper4b866272013-02-01 11:00:45 +00001031 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001032 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001033 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +00001034
Daniel Jasper4b866272013-02-01 11:00:45 +00001035 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001036 return Queue.top().second->State.Column;
1037 }
1038
1039 void reconstructPath(LineState &State, StateNode *Current) {
1040 // FIXME: This recursive implementation limits the possible number
1041 // of tokens per line if compiled into a binary with small stack space.
1042 // To become more independent of stack frame limitations we would need
1043 // to also change the TokenAnnotator.
1044 if (Current->Previous == NULL)
1045 return;
1046 reconstructPath(State, Current->Previous);
1047 DEBUG({
1048 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +00001049 llvm::errs()
1050 << "Penalty for splitting before "
1051 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1052 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001053 }
1054 });
1055 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +00001056 }
1057
Manuel Klimekaf491072013-02-13 10:54:19 +00001058 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001059 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001060 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001061 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001062 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1063 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001064 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001065 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001066 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001067 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001068 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001069 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1070
1071 StateNode *Node = new (Allocator.Allocate())
1072 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001073 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001074 if (Node->State.Column > getColumnLimit()) {
1075 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001076 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001077 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001078
1079 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1080 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001081 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001082
Daniel Jasper4b866272013-02-01 11:00:45 +00001083 /// \brief Returns \c true, if a line break after \p State is allowed.
1084 bool canBreak(const LineState &State) {
1085 if (!State.NextToken->CanBreakBefore &&
1086 !(State.NextToken->is(tok::r_brace) &&
1087 State.Stack.back().BreakBeforeClosingBrace))
1088 return false;
1089 // Trying to insert a parameter on a new line if there are already more than
1090 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +00001091 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001092 State.Stack.back().AvoidBinPacking)
1093 return false;
1094 return true;
1095 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001096
Daniel Jasper4b866272013-02-01 11:00:45 +00001097 /// \brief Returns \c true, if a line break after \p State is mandatory.
1098 bool mustBreak(const LineState &State) {
1099 if (State.NextToken->MustBreakBefore)
1100 return true;
1101 if (State.NextToken->is(tok::r_brace) &&
1102 State.Stack.back().BreakBeforeClosingBrace)
1103 return true;
1104 if (State.NextToken->Parent->is(tok::semi) &&
1105 State.LineContainsContinuedForLoopSection)
1106 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001107 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +00001108 State.NextToken->is(tok::question) ||
1109 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001110 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +00001111 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +00001112 State.NextToken->isNot(tok::r_paren) &&
1113 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001114 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +00001115 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1116 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001117 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001118 State.NextToken->LongestObjCSelectorName == 0 &&
1119 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001120 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001121 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1122 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001123 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001124 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001125 if (State.NextToken->Type == TT_InlineASMColon)
1126 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +00001127 // This prevents breaks like:
1128 // ...
1129 // SomeParameter, OtherParameter).DoSomething(
1130 // ...
1131 // As they hide "DoSomething" and generally bad for readability.
1132 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1133 getRemainingLength(State) + State.Column > getColumnLimit() &&
1134 State.ParenLevel < State.StartOfLineLevel)
1135 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001136 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 }
1138
Daniel Jasper9b334242013-03-15 14:57:30 +00001139 // Returns the total number of columns required for the remaining tokens.
1140 unsigned getRemainingLength(const LineState &State) {
1141 if (State.NextToken && State.NextToken->Parent)
1142 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1143 return 0;
1144 }
1145
Daniel Jasperf7935112012-12-03 18:12:45 +00001146 FormatStyle Style;
1147 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001148 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001149 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001150 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001151 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001152
1153 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1154 QueueType Queue;
1155 // Increasing count of \c StateNode items we have created. This is used
1156 // to create a deterministic order independent of the container.
1157 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001158};
1159
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001160class LexerBasedFormatTokenSource : public FormatTokenSource {
1161public:
1162 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001163 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001164 IdentTable(Lex.getLangOpts()) {
1165 Lex.SetKeepWhitespaceMode(true);
1166 }
1167
1168 virtual FormatToken getNextToken() {
1169 if (GreaterStashed) {
1170 FormatTok.NewlinesBefore = 0;
1171 FormatTok.WhiteSpaceStart =
1172 FormatTok.Tok.getLocation().getLocWithOffset(1);
1173 FormatTok.WhiteSpaceLength = 0;
1174 GreaterStashed = false;
1175 return FormatTok;
1176 }
1177
1178 FormatTok = FormatToken();
1179 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001180 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001181 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001182 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1183 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184
1185 // Consume and record whitespace until we find a significant token.
1186 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001187 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001188 if (Newlines > 0)
1189 FormatTok.LastNewlineOffset =
1190 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001191 unsigned EscapedNewlines = Text.count("\\\n");
1192 FormatTok.NewlinesBefore += Newlines;
1193 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001194 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1195
1196 if (FormatTok.Tok.is(tok::eof))
1197 return FormatTok;
1198 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001199 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001200 }
Manuel Klimekef920692013-01-07 07:56:50 +00001201
1202 // Now FormatTok is the next non-whitespace token.
1203 FormatTok.TokenLength = Text.size();
1204
Manuel Klimek1abf7892013-01-04 23:34:14 +00001205 // In case the token starts with escaped newlines, we want to
1206 // take them into account as whitespace - this pattern is quite frequent
1207 // in macro definitions.
1208 // FIXME: What do we want to do with other escaped spaces, and escaped
1209 // spaces or newlines in the middle of tokens?
1210 // FIXME: Add a more explicit test.
1211 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001212 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001213 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001214 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001215 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001216 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001217 }
1218
1219 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001220 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001221 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001222 FormatTok.Tok.setKind(Info.getTokenID());
1223 }
1224
1225 if (FormatTok.Tok.is(tok::greatergreater)) {
1226 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001227 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228 GreaterStashed = true;
1229 }
1230
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001231 // If we reformat comments, we remove trailing whitespace. Update the length
1232 // accordingly.
1233 if (FormatTok.Tok.is(tok::comment))
1234 FormatTok.TokenLength = Text.rtrim().size();
1235
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001236 return FormatTok;
1237 }
1238
Nico Weber29f9dea2013-02-11 15:32:15 +00001239 IdentifierTable &getIdentTable() { return IdentTable; }
1240
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001241private:
1242 FormatToken FormatTok;
1243 bool GreaterStashed;
1244 Lexer &Lex;
1245 SourceManager &SourceMgr;
1246 IdentifierTable IdentTable;
1247
1248 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001249 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001250 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1251 Tok.getLength());
1252 }
1253};
1254
Daniel Jasperf7935112012-12-03 18:12:45 +00001255class Formatter : public UnwrappedLineConsumer {
1256public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001257 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1258 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001259 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001260 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001261 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001262
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001263 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001264
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001265 tooling::Replacements format() {
1266 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1267 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1268 StructuralError = Parser.parse();
1269 unsigned PreviousEndOfLineColumn = 0;
1270 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1271 Tokens.getIdentTable().get("in"));
1272 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1273 Annotator.annotate(AnnotatedLines[i]);
1274 }
1275 deriveLocalStyle();
1276 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1277 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper0f8ed9e2013-03-13 15:53:12 +00001278
1279 // Adapt level to the next line if this is a comment.
1280 // FIXME: Can/should this be done in the UnwrappedLineParser?
1281 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1282 AnnotatedLines[i].First.Children.empty() &&
1283 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1284 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001285 }
1286 std::vector<int> IndentForLevel;
1287 bool PreviousLineWasTouched = false;
1288 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1289 E = AnnotatedLines.end();
1290 I != E; ++I) {
1291 const AnnotatedLine &TheLine = *I;
1292 const FormatToken &FirstTok = TheLine.First.FormatTok;
1293 int Offset = getIndentOffset(TheLine.First);
1294 while (IndentForLevel.size() <= TheLine.Level)
1295 IndentForLevel.push_back(-1);
1296 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001297 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001298 if (TheLine.First.is(tok::eof)) {
1299 if (PreviousLineWasTouched) {
1300 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1301 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001302 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001303 }
1304 } else if (TheLine.Type != LT_Invalid &&
1305 (WasMoved || touchesLine(TheLine))) {
1306 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1307 unsigned Indent = LevelIndent;
1308 if (static_cast<int>(Indent) + Offset >= 0)
1309 Indent += Offset;
1310 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001311 Indent = LevelIndent =
1312 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001313 } else {
1314 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1315 PreviousEndOfLineColumn);
1316 }
1317 tryFitMultipleLinesInOne(Indent, I, E);
1318 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1319 TheLine.First, Whitespaces,
1320 StructuralError);
1321 PreviousEndOfLineColumn =
1322 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1323 IndentForLevel[TheLine.Level] = LevelIndent;
1324 PreviousLineWasTouched = true;
1325 } else {
1326 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1327 unsigned Indent =
1328 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1329 unsigned LevelIndent = Indent;
1330 if (static_cast<int>(LevelIndent) - Offset >= 0)
1331 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001332 if (TheLine.First.isNot(tok::comment))
1333 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001334
1335 // Remove trailing whitespace of the previous line if it was touched.
1336 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1337 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1338 PreviousEndOfLineColumn);
1339 }
1340 // If we did not reformat this unwrapped line, the column at the end of
1341 // the last token is unchanged - thus, we can calculate the end of the
1342 // last token.
1343 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1344 PreviousEndOfLineColumn =
1345 SourceMgr.getSpellingColumnNumber(LastLoc) +
1346 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1347 PreviousLineWasTouched = false;
1348 }
1349 }
1350 return Whitespaces.generateReplacements();
1351 }
1352
1353private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001354 void deriveLocalStyle() {
1355 unsigned CountBoundToVariable = 0;
1356 unsigned CountBoundToType = 0;
1357 bool HasCpp03IncompatibleFormat = false;
1358 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1359 if (AnnotatedLines[i].First.Children.empty())
1360 continue;
1361 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1362 while (!Tok->Children.empty()) {
1363 if (Tok->Type == TT_PointerOrReference) {
1364 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1365 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1366 if (SpacesBefore && !SpacesAfter)
1367 ++CountBoundToVariable;
1368 else if (!SpacesBefore && SpacesAfter)
1369 ++CountBoundToType;
1370 }
1371
Daniel Jasper400adc62013-02-08 15:28:42 +00001372 if (Tok->Type == TT_TemplateCloser &&
1373 Tok->Parent->Type == TT_TemplateCloser &&
1374 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001375 HasCpp03IncompatibleFormat = true;
1376 Tok = &Tok->Children[0];
1377 }
1378 }
1379 if (Style.DerivePointerBinding) {
1380 if (CountBoundToType > CountBoundToVariable)
1381 Style.PointerBindsToType = true;
1382 else if (CountBoundToType < CountBoundToVariable)
1383 Style.PointerBindsToType = false;
1384 }
1385 if (Style.Standard == FormatStyle::LS_Auto) {
1386 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1387 : FormatStyle::LS_Cpp03;
1388 }
1389 }
1390
Manuel Klimekb95f5452013-02-08 17:38:27 +00001391 /// \brief Get the indent of \p Level from \p IndentForLevel.
1392 ///
1393 /// \p IndentForLevel must contain the indent for the level \c l
1394 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1395 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001396 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001397 if (IndentForLevel[Level] != -1)
1398 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001399 if (Level == 0)
1400 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001401 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001402 }
1403
1404 /// \brief Get the offset of the line relatively to the level.
1405 ///
1406 /// For example, 'public:' labels in classes are offset by 1 or 2
1407 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001408 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001409 bool IsAccessModifier = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001410 if (RootToken.isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
Manuel Klimekb95f5452013-02-08 17:38:27 +00001411 IsAccessModifier = true;
1412 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1413 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1414 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1415 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1416 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1417 IsAccessModifier = true;
1418
1419 if (IsAccessModifier)
1420 return Style.AccessModifierOffset;
1421 return 0;
1422 }
1423
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001424 /// \brief Tries to merge lines into one.
1425 ///
1426 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1427 /// if possible; note that \c I will be incremented when lines are merged.
1428 ///
1429 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001430 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001431 std::vector<AnnotatedLine>::iterator &I,
1432 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001433 // We can never merge stuff if there are trailing line comments.
1434 if (I->Last->Type == TT_LineComment)
1435 return;
1436
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001437 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001438 // If we already exceed the column limit, we set 'Limit' to 0. The different
1439 // tryMerge..() functions can then decide whether to still do merging.
1440 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001441
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001442 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001443 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001444
Daniel Jasper25837aa2013-01-14 14:14:23 +00001445 if (I->Last->is(tok::l_brace)) {
1446 tryMergeSimpleBlock(I, E, Limit);
1447 } else if (I->First.is(tok::kw_if)) {
1448 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001449 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1450 I->First.FormatTok.IsFirst)) {
1451 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001452 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001453 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001454 }
1455
Daniel Jasper39825ea2013-01-14 15:40:57 +00001456 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1457 std::vector<AnnotatedLine>::iterator E,
1458 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001459 if (Limit == 0)
1460 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001461 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001462 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1463 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001464 if (I + 2 != E && (I + 2)->InPPDirective &&
1465 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1466 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001467 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001468 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001469 join(Line, *(++I));
1470 }
1471
Daniel Jasper25837aa2013-01-14 14:14:23 +00001472 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1473 std::vector<AnnotatedLine>::iterator E,
1474 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001475 if (Limit == 0)
1476 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001477 if (!Style.AllowShortIfStatementsOnASingleLine)
1478 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001479 if ((I + 1)->InPPDirective != I->InPPDirective ||
1480 ((I + 1)->InPPDirective &&
1481 (I + 1)->First.FormatTok.HasUnescapedNewline))
1482 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001483 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001484 if (Line.Last->isNot(tok::r_paren))
1485 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001486 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001487 return;
1488 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1489 return;
1490 // Only inline simple if's (no nested if or else).
1491 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1492 return;
1493 join(Line, *(++I));
1494 }
1495
1496 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001497 std::vector<AnnotatedLine>::iterator E,
1498 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001499 // First, check that the current line allows merging. This is the case if
1500 // we're not in a control flow statement and the last token is an opening
1501 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001502 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001503 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1504 tok::kw_else, tok::kw_try, tok::kw_catch,
1505 tok::kw_for,
1506 // This gets rid of all ObjC @ keywords and methods.
1507 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001508 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001509
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001510 AnnotatedToken *Tok = &(I + 1)->First;
1511 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001512 !Tok->MustBreakBefore) {
1513 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001514 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001515 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001516 join(Line, *(I + 1));
1517 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001518 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001519 // Check that we still have three lines and they fit into the limit.
1520 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1521 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001522 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001523
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001524 // Second, check that the next line does not contain any braces - if it
1525 // does, readability declines when putting it into a single line.
1526 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1527 return;
1528 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001529 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001530 return;
1531 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1532 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001533
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001534 // Last, check that the third line contains a single closing brace.
1535 Tok = &(I + 2)->First;
1536 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1537 Tok->MustBreakBefore)
1538 return;
1539
1540 join(Line, *(I + 1));
1541 join(Line, *(I + 2));
1542 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001543 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001544 }
1545
1546 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1547 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001548 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1549 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001550 }
1551
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001553 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001554 A.Last->Children.push_back(B.First);
1555 while (!A.Last->Children.empty()) {
1556 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001557 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001558 A.Last = &A.Last->Children[0];
1559 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001560 }
1561
Daniel Jasper97b89482013-03-13 07:49:51 +00001562 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001563 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1564 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1565 Ranges[i].getBegin()) &&
1566 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1567 Range.getBegin()))
1568 return true;
1569 }
1570 return false;
1571 }
1572
1573 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001574 const FormatToken *First = &TheLine.First.FormatTok;
1575 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001576 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001577 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1578 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001579 return touchesRanges(LineRange);
1580 }
1581
1582 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1583 const FormatToken *First = &TheLine.First.FormatTok;
1584 CharSourceRange LineRange = CharSourceRange::getCharRange(
1585 First->WhiteSpaceStart,
1586 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1587 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001588 }
1589
1590 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001591 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001592 }
1593
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001594 /// \brief Add a new line and the required indent before the first Token
1595 /// of the \c UnwrappedLine if there was no structural parsing error.
1596 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001597 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1598 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001599 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001600
Daniel Jasperbbc84152013-01-29 11:27:30 +00001601 unsigned Newlines =
1602 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001603 if (Newlines == 0 && !Tok.IsFirst)
1604 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001605
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001606 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001607 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001608 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001609 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001610 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001611 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001612 }
1613
Alexander Kornienko116ba682013-01-14 11:34:14 +00001614 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001615 FormatStyle Style;
1616 Lexer &Lex;
1617 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001618 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001619 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001620 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001621 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001622};
1623
Daniel Jasperbbc84152013-01-29 11:27:30 +00001624tooling::Replacements
1625reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1626 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001627 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001628 OwningPtr<DiagnosticConsumer> DiagPrinter;
1629 if (DiagClient == 0) {
1630 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1631 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1632 DiagClient = DiagPrinter.get();
1633 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001634 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001635 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001636 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001637 Diagnostics.setSourceManager(&SourceMgr);
1638 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001639 return formatter.format();
1640}
1641
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001642LangOptions getFormattingLangOpts() {
1643 LangOptions LangOpts;
1644 LangOpts.CPlusPlus = 1;
1645 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001646 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001647 LangOpts.Bool = 1;
1648 LangOpts.ObjC1 = 1;
1649 LangOpts.ObjC2 = 1;
1650 return LangOpts;
1651}
1652
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001653} // namespace format
1654} // namespace clang