blob: 245b7f60a6b3cce9c127fcf7a0725b620947669d [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"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000030#include <string>
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000051 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000065 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000067 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000068 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000069 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000070 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000071 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000078 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000079 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
80 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000081 return ChromiumStyle;
82}
83
Daniel Jasper94f0e132013-02-06 20:07:35 +000084static bool isTrailingComment(const AnnotatedToken &Tok) {
85 return Tok.is(tok::comment) &&
86 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
87}
88
Daniel Jasperd1ae3582013-03-20 12:37:50 +000089static bool isComparison(const AnnotatedToken &Tok) {
90 prec::Level Precedence = getPrecedence(Tok);
91 return Tok.Type == TT_BinaryOperator &&
92 (Precedence == prec::Equality || Precedence == prec::Relational);
93}
94
Daniel Jasperacc33662013-02-08 08:22:00 +000095// Returns the length of everything up to the first possible line break after
96// the ), ], } or > matching \c Tok.
97static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
98 if (Tok.MatchingParen == NULL)
99 return 0;
100 AnnotatedToken *End = Tok.MatchingParen;
101 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
102 End = &End->Children[0];
103 }
104 return End->TotalLength - Tok.TotalLength + 1;
105}
106
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000107static size_t
108calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
109 // In preprocessor directives reserve two chars for trailing " \"
110 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
111}
112
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000113/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000114///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115/// This includes special handling for certain constructs, e.g. the alignment of
116/// trailing line comments.
117class WhitespaceManager {
118public:
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000119 WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
120 : SourceMgr(SourceMgr), Style(Style) {}
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000121
122 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
123 /// each \c AnnotatedToken.
124 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000125 unsigned Spaces, unsigned WhitespaceStartColumn) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000126 // 2+ newlines mean an empty line separating logic scopes.
127 if (NewLines >= 2)
128 alignComments();
129
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000130 SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
131 bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
132 Tok.FormatTok.TokenLength > Style.ColumnLimit;
133
Daniel Jasper304a9862013-01-21 22:49:20 +0000134 // Align line comments if they are trailing or if they continue other
135 // trailing comments.
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000136 if (isTrailingComment(Tok)) {
137 // Remove the comment's trailing whitespace.
138 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
139 Replaces.insert(tooling::Replacement(
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000140 SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000141 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
142
143 // Align comment with other comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000144 if ((Tok.Parent != NULL || !Comments.empty()) &&
145 !LineExceedsColumnLimit) {
146 StoredComment Comment;
147 Comment.Tok = Tok.FormatTok;
148 Comment.Spaces = Spaces;
149 Comment.NewLines = NewLines;
150 Comment.MinColumn =
151 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
152 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
153 Comment.Untouchable = false;
154 Comments.push_back(Comment);
155 return;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000156 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000157 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000158
159 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000160 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000161 alignComments();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000162
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000163 if (Tok.Type == TT_BlockComment) {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000164 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000165 } else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
166 StringRef Line(SourceMgr.getCharacterData(TokenLoc),
167 Tok.FormatTok.TokenLength);
168 int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
169 StringRef Prefix = getLineCommentPrefix(Line);
170 std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
171 splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
172 StartColumn + Prefix.size(), NewPrefix,
173 /*InPPDirective=*/ false,
174 /*CommentHasMoreLines=*/ false);
175 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000176
Manuel Klimek1998ea22013-02-20 10:15:13 +0000177 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000178 }
179
180 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
181 /// backslashes to escape newlines inside a preprocessor directive.
182 ///
183 /// This function and \c replaceWhitespace have the same behavior if
184 /// \c Newlines == 0.
185 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000186 unsigned Spaces, unsigned WhitespaceStartColumn) {
187 if (Tok.Type == TT_BlockComment)
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000188 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000189
190 storeReplacement(Tok.FormatTok,
191 getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000192 }
193
194 /// \brief Inserts a line break into the middle of a token.
195 ///
196 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
197 /// break and \p Postfix before the rest of the token starts in the next line.
198 ///
199 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
200 /// used to generate the correct line break.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000201 void breakToken(const FormatToken &Tok, unsigned Offset,
202 unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
203 bool InPPDirective, unsigned Spaces,
204 unsigned WhitespaceStartColumn) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000205 std::string NewLineText;
206 if (!InPPDirective)
207 NewLineText = getNewLineText(1, Spaces);
208 else
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000209 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000210 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000211 SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
212 Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
213 ReplacementText));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000214 }
215
216 /// \brief Returns all the \c Replacements created during formatting.
217 const tooling::Replacements &generateReplacements() {
218 alignComments();
219 return Replaces;
220 }
221
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000222 void addUntouchableComment(unsigned Column) {
223 StoredComment Comment;
224 Comment.MinColumn = Column;
225 Comment.MaxColumn = Column;
226 Comment.Untouchable = true;
227 Comments.push_back(Comment);
228 }
229
Manuel Klimek1998ea22013-02-20 10:15:13 +0000230private:
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000231 static StringRef getLineCommentPrefix(StringRef Comment) {
232 const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
233 for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
234 if (Comment.startswith(KnownPrefixes[i]))
235 return KnownPrefixes[i];
236 return "";
237 }
238
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000239 /// \brief Finds a common prefix of lines of a block comment to properly
240 /// indent (and possibly decorate with '*'s) added lines.
241 ///
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000242 /// The first line is ignored (it's special and starts with /*). The number of
243 /// lines should be more than one.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000244 static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
245 const char *PrefixChars = " *") {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000246 assert(Lines.size() > 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000247 StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
248 for (size_t i = 2; i < Lines.size(); ++i) {
249 for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
250 if (Prefix[j] != Lines[i][j]) {
251 Prefix = Prefix.substr(0, j);
252 break;
253 }
254 }
255 }
256 return Prefix;
257 }
258
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000259 /// \brief Splits one line in a line or block comment, if it doesn't fit to
260 /// provided column limit. Removes trailing whitespace in each line.
261 ///
262 /// \param Line points to the line contents without leading // or /*.
263 ///
264 /// \param StartColumn is the column where the first character of Line will be
265 /// located after formatting.
266 ///
267 /// \param LinePrefix is inserted after each line break.
268 ///
269 /// When \param InPPDirective is true, each line break will be preceded by a
270 /// backslash in the last column to make line breaks inside the comment
271 /// visually consistent with line breaks outside the comment. This only makes
272 /// sense for block comments.
273 ///
274 /// When \param CommentHasMoreLines is false, no line breaks/trailing
275 /// backslashes will be inserted after it.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000276 void splitLineInComment(const FormatToken &Tok, StringRef Line,
277 size_t StartColumn, StringRef LinePrefix,
278 bool InPPDirective, bool CommentHasMoreLines,
279 const char *WhiteSpaceChars = " ") {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000280 size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000281 const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000282
283 StringRef TrimmedLine = Line.rtrim();
284 int TrailingSpaceLength = Line.size() - TrimmedLine.size();
285
286 // Don't touch leading whitespace.
287 Line = TrimmedLine.ltrim();
288 StartColumn += TrimmedLine.size() - Line.size();
289
290 while (Line.size() + StartColumn > ColumnLimit) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000291 // Try to break at the last whitespace before the column limit.
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000292 size_t SpacePos =
293 Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000294 if (SpacePos == StringRef::npos) {
295 // Try to find any whitespace in the line.
296 SpacePos = Line.find_first_of(WhiteSpaceChars);
297 if (SpacePos == StringRef::npos) // No whitespace found, give up.
298 break;
299 }
300
301 StringRef NextCut = Line.substr(0, SpacePos).rtrim();
302 StringRef RemainingLine = Line.substr(SpacePos).ltrim();
303 if (RemainingLine.empty())
304 break;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000305
306 if (RemainingLine == "*/" && LinePrefix.endswith("* "))
307 LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
308
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000309 Line = RemainingLine;
310
311 size_t ReplaceChars = Line.begin() - NextCut.end();
312 breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000313 InPPDirective, 0, NextCut.size() + StartColumn);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000314 StartColumn = LinePrefix.size();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000315 }
316
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000317 if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
318 // Remove trailing whitespace/insert backslash. + 1 is for \n
319 breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
320 InPPDirective, 0, Line.size() + StartColumn);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000321 }
322 }
323
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000324 /// \brief Changes indentation of all lines in a block comment by Indent,
325 /// removes trailing whitespace from each line, splits lines that end up
326 /// exceeding the column limit.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000327 void indentBlockComment(const AnnotatedToken &Tok, int Indent,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000328 int WhitespaceStartColumn, int NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000329 bool InPPDirective) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000330 assert(Tok.Type == TT_BlockComment);
331 int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000332 const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
333 const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
334 const int IndentDelta = Indent - CurrentIndent;
335 const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
336 Tok.FormatTok.TokenLength);
337 assert(Text.startswith("/*") && Text.endswith("*/"));
338
339 SmallVector<StringRef, 16> Lines;
340 Text.split(Lines, "\n");
341
342 if (IndentDelta > 0) {
343 std::string WhiteSpace(IndentDelta, ' ');
344 for (size_t i = 1; i < Lines.size(); ++i) {
345 Replaces.insert(tooling::Replacement(
346 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
347 0, WhiteSpace));
348 }
349 } else if (IndentDelta < 0) {
350 std::string WhiteSpace(-IndentDelta, ' ');
351 // Check that the line is indented enough.
352 for (size_t i = 1; i < Lines.size(); ++i) {
353 if (!Lines[i].startswith(WhiteSpace))
354 return;
355 }
356 for (size_t i = 1; i < Lines.size(); ++i) {
357 Replaces.insert(tooling::Replacement(
358 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
359 -IndentDelta, ""));
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000360 }
361 }
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000362
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000363 // Split long lines in comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000364 size_t OldPrefixSize = 0;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000365 std::string NewPrefix;
366 if (Lines.size() > 1) {
367 StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000368 OldPrefixSize = CurrentPrefix.size();
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000369 NewPrefix = (IndentDelta < 0)
370 ? CurrentPrefix.substr(-IndentDelta).str()
371 : std::string(IndentDelta, ' ') + CurrentPrefix.str();
372 if (CurrentPrefix.endswith("*")) {
373 NewPrefix += " ";
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000374 ++OldPrefixSize;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000375 }
376 } else if (Tok.Parent == 0) {
377 NewPrefix = std::string(StartColumn, ' ') + " * ";
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000378 }
379
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000380 StartColumn += 2;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000381 for (size_t i = 0; i < Lines.size(); ++i) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000382 StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000383 splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
384 InPPDirective, i != Lines.size() - 1);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000385 StartColumn = NewPrefix.size();
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000386 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000387 }
388
Manuel Klimek1998ea22013-02-20 10:15:13 +0000389 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
390 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
391 }
392
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000393 std::string getNewLineText(unsigned NewLines, unsigned Spaces,
394 unsigned WhitespaceStartColumn) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000395 std::string NewLineText;
396 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000397 unsigned Offset =
398 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000399 for (unsigned i = 0; i < NewLines; ++i) {
400 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
401 NewLineText += "\\\n";
402 Offset = 0;
403 }
404 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000405 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000406 }
407
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000408 /// \brief Structure to store a comment for later layout and alignment.
409 struct StoredComment {
410 FormatToken Tok;
411 unsigned MinColumn;
412 unsigned MaxColumn;
413 unsigned NewLines;
414 unsigned Spaces;
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000415 bool Untouchable;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000416 };
417 SmallVector<StoredComment, 16> Comments;
418 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
419
420 /// \brief Try to align all stashed comments.
421 void alignComments() {
422 unsigned MinColumn = 0;
423 unsigned MaxColumn = UINT_MAX;
424 comment_iterator Start = Comments.begin();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000425 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000426 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
427 alignComments(Start, I, MinColumn);
428 MinColumn = I->MinColumn;
429 MaxColumn = I->MaxColumn;
430 Start = I;
431 } else {
432 MinColumn = std::max(MinColumn, I->MinColumn);
433 MaxColumn = std::min(MaxColumn, I->MaxColumn);
434 }
435 }
436 alignComments(Start, Comments.end(), MinColumn);
437 Comments.clear();
438 }
439
440 /// \brief Put all the comments between \p I and \p E into \p Column.
441 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
442 while (I != E) {
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000443 if (!I->Untouchable) {
444 unsigned Spaces = I->Spaces + Column - I->MinColumn;
Alexander Kornienkofd433362013-03-27 17:08:02 +0000445 storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000446 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000447 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000448 }
449 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000450
451 /// \brief Stores \p Text as the replacement for the whitespace in front of
452 /// \p Tok.
453 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000454 // Don't create a replacement, if it does not change anything.
455 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
456 Tok.WhiteSpaceLength) == Text)
457 return;
458
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000459 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
460 Tok.WhiteSpaceLength, Text));
461 }
462
463 SourceManager &SourceMgr;
464 tooling::Replacements Replaces;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000465 const FormatStyle &Style;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000466};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000467
Daniel Jasperf7935112012-12-03 18:12:45 +0000468class UnwrappedLineFormatter {
469public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000470 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000471 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000472 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000473 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000474 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000475 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000476 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000477
Manuel Klimek1abf7892013-01-04 23:34:14 +0000478 /// \brief Formats an \c UnwrappedLine.
479 ///
480 /// \returns The column after the last token in the last line of the
481 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000482 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000483 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000484 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000485 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000486 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000487 State.Stack.push_back(
488 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
489 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000490 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000491 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000492 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000493 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000494 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000495
Manuel Klimek24998102013-01-16 14:55:28 +0000496 DEBUG({
497 DebugTokenState(*State.NextToken);
498 });
499
Daniel Jaspere9de2602012-12-06 09:56:08 +0000500 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000501 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000502
Daniel Jasper4b866272013-02-01 11:00:45 +0000503 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000504 unsigned ColumnLimit = Style.ColumnLimit;
505 if (NextLine && NextLine->InPPDirective &&
506 !NextLine->First.FormatTok.HasUnescapedNewline)
507 ColumnLimit = getColumnLimit();
508 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000509 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000510 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000511 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000512 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000514
Daniel Jasperacc33662013-02-08 08:22:00 +0000515 // If the ObjC method declaration does not fit on a line, we should format
516 // it with one arg per line.
517 if (Line.Type == LT_ObjCMethodDecl)
518 State.Stack.back().BreakBeforeParameter = true;
519
Daniel Jasper4b866272013-02-01 11:00:45 +0000520 // Find best solution in solution space.
521 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 }
523
524private:
Manuel Klimek24998102013-01-16 14:55:28 +0000525 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
526 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000527 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
528 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000529 llvm::errs();
530 }
531
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000533 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
534 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000535 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
536 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000537 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000538 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
539 StartOfFunctionCall(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000540
Daniel Jasperf7935112012-12-03 18:12:45 +0000541 /// \brief The position to which a specific parenthesis level needs to be
542 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000544
Daniel Jaspere9de2602012-12-06 09:56:08 +0000545 /// \brief The position of the last space on each level.
546 ///
547 /// Used e.g. to break like:
548 /// functionCall(Parameter, otherCall(
549 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000550 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000551
Daniel Jaspere9de2602012-12-06 09:56:08 +0000552 /// \brief The position the first "<<" operator encountered on each level.
553 ///
554 /// Used to align "<<" operators. 0 if no such operator has been encountered
555 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000557
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000558 /// \brief Whether a newline needs to be inserted before the block's closing
559 /// brace.
560 ///
561 /// We only want to insert a newline before the closing brace if there also
562 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000563 bool BreakBeforeClosingBrace;
564
Daniel Jasperca6623b2013-01-28 12:45:14 +0000565 /// \brief The column of a \c ? in a conditional expression;
566 unsigned QuestionColumn;
567
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000568 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
569 /// lines, in this context.
570 bool AvoidBinPacking;
571
572 /// \brief Break after the next comma (or all the commas in this context if
573 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000574 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000575
576 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000577 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000578
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000579 /// \brief The position of the colon in an ObjC method declaration/call.
580 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000581
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000582 /// \brief The start of the most recent function in a builder-type call.
583 unsigned StartOfFunctionCall;
584
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 bool operator<(const ParenState &Other) const {
586 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000587 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000588 if (LastSpace != Other.LastSpace)
589 return LastSpace < Other.LastSpace;
590 if (FirstLessLess != Other.FirstLessLess)
591 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000592 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
593 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000594 if (QuestionColumn != Other.QuestionColumn)
595 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000596 if (AvoidBinPacking != Other.AvoidBinPacking)
597 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000598 if (BreakBeforeParameter != Other.BreakBeforeParameter)
599 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000600 if (HasMultiParameterLine != Other.HasMultiParameterLine)
601 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000602 if (ColonPos != Other.ColonPos)
603 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000604 if (StartOfFunctionCall != Other.StartOfFunctionCall)
605 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000606 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000607 }
608 };
609
610 /// \brief The current state when indenting a unwrapped line.
611 ///
612 /// As the indenting tries different combinations this is copied by value.
613 struct LineState {
614 /// \brief The number of used columns in the current line.
615 unsigned Column;
616
617 /// \brief The token that needs to be next formatted.
618 const AnnotatedToken *NextToken;
619
Daniel Jasperbbc84152013-01-29 11:27:30 +0000620 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000621 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000622 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000623 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000624
625 /// \brief \c true if this line contains a continued for-loop section.
626 bool LineContainsContinuedForLoopSection;
627
Daniel Jasper400adc62013-02-08 15:28:42 +0000628 /// \brief The level of nesting inside (), [], <> and {}.
629 unsigned ParenLevel;
630
Daniel Jasper40c36c52013-02-18 11:05:07 +0000631 /// \brief The \c ParenLevel at the start of this line.
632 unsigned StartOfLineLevel;
633
Manuel Klimek02f640a2013-02-20 15:25:48 +0000634 /// \brief The start column of the string literal, if we're in a string
635 /// literal sequence, 0 otherwise.
636 unsigned StartOfStringLiteral;
637
Daniel Jasper337816e2013-01-11 10:22:12 +0000638 /// \brief A stack keeping track of properties applying to parenthesis
639 /// levels.
640 std::vector<ParenState> Stack;
641
642 /// \brief Comparison operator to be able to used \c LineState in \c map.
643 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000644 if (NextToken != Other.NextToken)
645 return NextToken < Other.NextToken;
646 if (Column != Other.Column)
647 return Column < Other.Column;
648 if (VariablePos != Other.VariablePos)
649 return VariablePos < Other.VariablePos;
650 if (LineContainsContinuedForLoopSection !=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000651 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000652 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000653 if (ParenLevel != Other.ParenLevel)
654 return ParenLevel < Other.ParenLevel;
655 if (StartOfLineLevel != Other.StartOfLineLevel)
656 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000657 if (StartOfStringLiteral != Other.StartOfStringLiteral)
658 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000659 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 }
661 };
662
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000663 /// \brief Appends the next token to \p State and updates information
664 /// necessary for indentation.
665 ///
666 /// Puts the token on the current line if \p Newline is \c true and adds a
667 /// line break and necessary indentation otherwise.
668 ///
669 /// If \p DryRun is \c false, also creates and stores the required
670 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000671 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000672 const AnnotatedToken &Current = *State.NextToken;
673 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000674
Daniel Jasper291f9362013-03-20 15:58:10 +0000675 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000676 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
677 State.NextToken->FormatTok.TokenLength;
678 if (State.NextToken->Children.empty())
679 State.NextToken = NULL;
680 else
681 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000682 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000683 }
684
Daniel Jasperf7935112012-12-03 18:12:45 +0000685 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000686 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000687 if (Current.is(tok::r_brace)) {
688 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000689 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000690 State.StartOfStringLiteral != 0) {
691 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000692 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000693 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000694 State.Stack.back().FirstLessLess != 0) {
695 State.Column = State.Stack.back().FirstLessLess;
696 } else if (State.ParenLevel != 0 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000697 (Previous.isOneOf(tok::equal, tok::coloncolon) ||
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000698 Current.isOneOf(tok::period, tok::arrow, tok::question) ||
699 isComparison(Previous))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000700 // Indent and extra 4 spaces after if we know the current expression is
701 // continued. Don't do that on the top level, as we already indent 4
702 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000703 State.Column = std::max(State.Stack.back().LastSpace,
704 State.Stack.back().Indent) + 4;
705 } else if (Current.Type == TT_ConditionalExpr) {
706 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000707 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000708 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
709 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000710 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000711 } else if (Previous.ClosesTemplateDeclaration ||
712 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000713 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000714 } else if (Current.Type == TT_ObjCSelectorName) {
715 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
716 State.Column =
717 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
718 } else {
719 State.Column = State.Stack.back().Indent;
720 State.Stack.back().ColonPos =
721 State.Column + Current.FormatTok.TokenLength;
722 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000723 } else if (Previous.Type == TT_ObjCMethodExpr ||
724 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000725 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000726 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000727 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000728 }
729
Daniel Jasper54a86022013-02-15 11:07:25 +0000730 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000731 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000732 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000733 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000734 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000735
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000736 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000737 unsigned NewLines = 1;
738 if (Current.Type == TT_LineComment)
739 NewLines =
740 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
741 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000742 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000743 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000744 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000745 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000746 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000747 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000748 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000749
Daniel Jasper400adc62013-02-08 15:28:42 +0000750 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000751 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000752
753 // Any break on this level means that the parent level has been broken
754 // and we need to avoid bin packing there.
755 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
756 State.Stack[i].BreakBeforeParameter = true;
757 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000758 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000759 State.Stack.back().BreakBeforeParameter = true;
760
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000761 // If we break after {, we should also break before the corresponding }.
762 if (Previous.is(tok::l_brace))
763 State.Stack.back().BreakBeforeClosingBrace = true;
764
765 if (State.Stack.back().AvoidBinPacking) {
766 // If we are breaking after '(', '{', '<', this is not bin packing
767 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000768 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000769 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
770 Line.MustBeDeclaration))
771 State.Stack.back().BreakBeforeParameter = true;
772 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000773 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000774 // FIXME: Put VariablePos into ParenState and remove second part of if().
775 if (Current.is(tok::equal) &&
776 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000777 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000778
Daniel Jaspereef30492013-02-11 12:36:37 +0000779 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000780
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000782 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000783
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000784 if (Current.Type == TT_ObjCSelectorName &&
785 State.Stack.back().ColonPos == 0) {
786 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000787 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000788 State.Stack.back().ColonPos =
789 State.Stack.back().Indent + Current.LongestObjCSelectorName;
790 else
791 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000792 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000793 }
794
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000795 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000796 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000797 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000798 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000799 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000800 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000801
Daniel Jaspere9de2602012-12-06 09:56:08 +0000802 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000803 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
804 // Treat the condition inside an if as if it was a second function
805 // parameter, i.e. let nested calls have an indent of 4.
806 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000807 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000808 // Top-level spaces are exempt as that mostly leads to better results.
809 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000810 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000811 Previous.Type == TT_ConditionalExpr ||
812 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000813 getPrecedence(Previous) != prec::Assignment)
814 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000815 else if (Previous.Type == TT_InheritanceColon)
816 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000817 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000818 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000819 Previous.Type == TT_TemplateOpener))
820 // If this function has multiple parameters, indent nested calls from
821 // the start of the first parameter.
822 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000824
Manuel Klimek1998ea22013-02-20 10:15:13 +0000825 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000826 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000827
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000828 /// \brief Mark the next token as consumed in \p State and modify its stacks
829 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000830 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000831 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000832 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000833
Daniel Jaspereead02b2013-02-14 08:42:54 +0000834 if (Current.Type == TT_InheritanceColon)
835 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000836 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
837 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000838 if (Current.is(tok::question))
839 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000840 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000841 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
842 State.Stack.back().StartOfFunctionCall =
843 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000844 if (Current.Type == TT_CtorInitializerColon) {
845 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
846 State.Stack.back().AvoidBinPacking = true;
847 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000848 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000849
Daniel Jasper400adc62013-02-08 15:28:42 +0000850 // Insert scopes created by fake parenthesis.
851 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
852 ParenState NewParenState = State.Stack.back();
853 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000854 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000855 State.Stack.push_back(NewParenState);
856 }
857
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000858 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000859 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000860 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000861 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000862 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000863 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000864 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000865 NewIndent = 2 + State.Stack.back().LastSpace;
866 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000867 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000868 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
869 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000870 AvoidBinPacking =
871 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000872 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000873 State.Stack.push_back(
874 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
875 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000876 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000877 }
878
Daniel Jasperacc33662013-02-08 08:22:00 +0000879 // If this '[' opens an ObjC call, determine whether all parameters fit into
880 // one line and put one per line if they don't.
881 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
882 Current.MatchingParen != NULL) {
883 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
884 State.Stack.back().BreakBeforeParameter = true;
885 }
886
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000887 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000888 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000889 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000890 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
891 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000892 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000893 --State.ParenLevel;
894 }
895
896 // Remove scopes created by fake parenthesis.
897 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
898 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000899 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000900
Manuel Klimek0c915712013-02-20 15:32:58 +0000901 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000902 State.StartOfStringLiteral = State.Column;
903 } else if (Current.isNot(tok::comment)) {
904 State.StartOfStringLiteral = 0;
905 }
906
Manuel Klimek1998ea22013-02-20 10:15:13 +0000907 State.Column += Current.FormatTok.TokenLength;
908
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000909 if (State.NextToken->Children.empty())
910 State.NextToken = NULL;
911 else
912 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000913
Manuel Klimek1998ea22013-02-20 10:15:13 +0000914 return breakProtrudingToken(Current, State, DryRun);
915 }
916
917 /// \brief If the current token sticks out over the end of the line, break
918 /// it if possible.
919 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
920 bool DryRun) {
921 if (Current.isNot(tok::string_literal))
922 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000923 // Only break up default narrow strings.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000924 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
925 if (!LiteralData || *LiteralData != '"')
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000926 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000927
928 unsigned Penalty = 0;
929 unsigned TailOffset = 0;
930 unsigned TailLength = Current.FormatTok.TokenLength;
931 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
932 unsigned OffsetFromStart = 0;
933 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000934 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000935 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000936 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000937 StringRef::size_type SplitPoint = getSplitPoint(
938 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000939 if (SplitPoint == StringRef::npos)
940 break;
941 assert(SplitPoint != 0);
942 // +2, because 'Text' starts after the opening quotes, and does not
943 // include the closing quote we need to insert.
944 unsigned WhitespaceStartColumn =
945 StartColumn + OffsetFromStart + SplitPoint + 2;
946 State.Stack.back().LastSpace = StartColumn;
947 if (!DryRun) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000948 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
949 0, "\"", "\"", Line.InPPDirective, StartColumn,
950 WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000951 }
952 TailOffset += SplitPoint + 1;
953 TailLength -= SplitPoint + 1;
954 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000955 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000956 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
957 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000958 }
959 State.Column = StartColumn + TailLength;
960 return Penalty;
961 }
962
963 StringRef::size_type
964 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000965 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000966 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000967 return SpaceOffset;
968 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000969 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000970 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000971 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
972 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000973 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000974 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000975 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000976 }
977
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000978 StringRef::size_type
979 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
980 StringRef::size_type NextEscape = Text.find('\\');
981 while (NextEscape != StringRef::npos && NextEscape < Offset) {
982 StringRef::size_type SequenceLength =
983 getEscapeSequenceLength(Text.substr(NextEscape));
984 if (Offset < NextEscape + SequenceLength)
985 return NextEscape;
986 NextEscape = Text.find('\\', NextEscape + SequenceLength);
987 }
988 return Offset;
989 }
990
991 unsigned getEscapeSequenceLength(StringRef Text) {
992 assert(Text[0] == '\\');
993 if (Text.size() < 2)
994 return 1;
995
996 switch (Text[1]) {
997 case 'u':
998 return 6;
999 case 'U':
1000 return 10;
1001 case 'x':
1002 return getHexLength(Text);
1003 default:
1004 if (Text[1] >= '0' && Text[1] <= '7')
1005 return getOctalLength(Text);
1006 return 2;
1007 }
1008 }
1009
1010 unsigned getHexLength(StringRef Text) {
1011 unsigned I = 2; // Point after '\x'.
1012 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
1013 (Text[I] >= 'a' && Text[I] <= 'f') ||
1014 (Text[I] >= 'A' && Text[I] <= 'F'))) {
1015 ++I;
1016 }
1017 return I;
1018 }
1019
1020 unsigned getOctalLength(StringRef Text) {
1021 unsigned I = 1;
1022 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
1023 ++I;
1024 }
1025 return I;
1026 }
1027
Daniel Jasper2df93312013-01-09 10:16:05 +00001028 unsigned getColumnLimit() {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +00001029 return calculateColumnLimit(Style, Line.InPPDirective);
Daniel Jasper2df93312013-01-09 10:16:05 +00001030 }
1031
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001032 /// \brief An edge in the solution space from \c Previous->State to \c State,
1033 /// inserting a newline dependent on the \c NewLine.
1034 struct StateNode {
1035 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001036 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001037 LineState State;
1038 bool NewLine;
1039 StateNode *Previous;
1040 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001041
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001042 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1043 ///
1044 /// In case of equal penalties, we want to prefer states that were inserted
1045 /// first. During state generation we make sure that we insert states first
1046 /// that break the line as late as possible.
1047 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1048
1049 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1050 /// \c State has the given \c OrderedPenalty.
1051 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1052
1053 /// \brief The BFS queue type.
1054 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1055 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001056
1057 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001059 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1060 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1061 /// find the shortest path (the one with lowest penalty) from \p InitialState
1062 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001063 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001064 std::set<LineState> Seen;
1065
Daniel Jasper4b866272013-02-01 11:00:45 +00001066 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001067 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001068 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1069 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1070 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001071
1072 // While not empty, take first element and follow edges.
1073 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001074 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001075 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001076 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001077 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001078 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001079 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001080 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001081
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001082 if (!Seen.insert(Node->State).second)
1083 // State already examined with lower penalty.
1084 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001085
Manuel Klimekaf491072013-02-13 10:54:19 +00001086 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1087 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001088 }
1089
1090 if (Queue.empty())
1091 // We were unable to find a solution, do nothing.
1092 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 return 0;
1094
Daniel Jasper4b866272013-02-01 11:00:45 +00001095 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001096 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001097 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +00001098
Daniel Jasper4b866272013-02-01 11:00:45 +00001099 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001100 return Queue.top().second->State.Column;
1101 }
1102
1103 void reconstructPath(LineState &State, StateNode *Current) {
1104 // FIXME: This recursive implementation limits the possible number
1105 // of tokens per line if compiled into a binary with small stack space.
1106 // To become more independent of stack frame limitations we would need
1107 // to also change the TokenAnnotator.
1108 if (Current->Previous == NULL)
1109 return;
1110 reconstructPath(State, Current->Previous);
1111 DEBUG({
1112 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +00001113 llvm::errs()
1114 << "Penalty for splitting before "
1115 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1116 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001117 }
1118 });
1119 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +00001120 }
1121
Manuel Klimekaf491072013-02-13 10:54:19 +00001122 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001123 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001124 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001125 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001126 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1127 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001128 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001129 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001130 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001131 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001132 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001133 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1134
1135 StateNode *Node = new (Allocator.Allocate())
1136 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001137 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001138 if (Node->State.Column > getColumnLimit()) {
1139 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001140 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001141 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001142
1143 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1144 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001145 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001146
Daniel Jasper4b866272013-02-01 11:00:45 +00001147 /// \brief Returns \c true, if a line break after \p State is allowed.
1148 bool canBreak(const LineState &State) {
1149 if (!State.NextToken->CanBreakBefore &&
1150 !(State.NextToken->is(tok::r_brace) &&
1151 State.Stack.back().BreakBeforeClosingBrace))
1152 return false;
1153 // Trying to insert a parameter on a new line if there are already more than
1154 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +00001155 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 State.Stack.back().AvoidBinPacking)
1157 return false;
1158 return true;
1159 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001160
Daniel Jasper4b866272013-02-01 11:00:45 +00001161 /// \brief Returns \c true, if a line break after \p State is mandatory.
1162 bool mustBreak(const LineState &State) {
1163 if (State.NextToken->MustBreakBefore)
1164 return true;
1165 if (State.NextToken->is(tok::r_brace) &&
1166 State.Stack.back().BreakBeforeClosingBrace)
1167 return true;
1168 if (State.NextToken->Parent->is(tok::semi) &&
1169 State.LineContainsContinuedForLoopSection)
1170 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001171 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +00001172 State.NextToken->is(tok::question) ||
1173 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001174 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +00001175 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +00001176 State.NextToken->isNot(tok::r_paren) &&
1177 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001178 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +00001179 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1180 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001181 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001182 State.NextToken->LongestObjCSelectorName == 0 &&
1183 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001184 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001185 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1186 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001187 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001188 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001189 if (State.NextToken->Type == TT_InlineASMColon)
1190 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +00001191 // This prevents breaks like:
1192 // ...
1193 // SomeParameter, OtherParameter).DoSomething(
1194 // ...
1195 // As they hide "DoSomething" and generally bad for readability.
1196 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1197 getRemainingLength(State) + State.Column > getColumnLimit() &&
1198 State.ParenLevel < State.StartOfLineLevel)
1199 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001200 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001201 }
1202
Daniel Jasper9b334242013-03-15 14:57:30 +00001203 // Returns the total number of columns required for the remaining tokens.
1204 unsigned getRemainingLength(const LineState &State) {
1205 if (State.NextToken && State.NextToken->Parent)
1206 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1207 return 0;
1208 }
1209
Daniel Jasperf7935112012-12-03 18:12:45 +00001210 FormatStyle Style;
1211 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001212 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001213 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001214 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001215 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001216
1217 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1218 QueueType Queue;
1219 // Increasing count of \c StateNode items we have created. This is used
1220 // to create a deterministic order independent of the container.
1221 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001222};
1223
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001224class LexerBasedFormatTokenSource : public FormatTokenSource {
1225public:
1226 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001227 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001228 IdentTable(Lex.getLangOpts()) {
1229 Lex.SetKeepWhitespaceMode(true);
1230 }
1231
1232 virtual FormatToken getNextToken() {
1233 if (GreaterStashed) {
1234 FormatTok.NewlinesBefore = 0;
1235 FormatTok.WhiteSpaceStart =
1236 FormatTok.Tok.getLocation().getLocWithOffset(1);
1237 FormatTok.WhiteSpaceLength = 0;
1238 GreaterStashed = false;
1239 return FormatTok;
1240 }
1241
1242 FormatTok = FormatToken();
1243 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001244 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001245 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001246 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1247 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001248
1249 // Consume and record whitespace until we find a significant token.
1250 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001251 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001252 if (Newlines > 0)
1253 FormatTok.LastNewlineOffset =
1254 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001255 unsigned EscapedNewlines = Text.count("\\\n");
1256 FormatTok.NewlinesBefore += Newlines;
1257 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001258 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1259
1260 if (FormatTok.Tok.is(tok::eof))
1261 return FormatTok;
1262 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001263 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001264 }
Manuel Klimekef920692013-01-07 07:56:50 +00001265
1266 // Now FormatTok is the next non-whitespace token.
1267 FormatTok.TokenLength = Text.size();
1268
Manuel Klimek1abf7892013-01-04 23:34:14 +00001269 // In case the token starts with escaped newlines, we want to
1270 // take them into account as whitespace - this pattern is quite frequent
1271 // in macro definitions.
1272 // FIXME: What do we want to do with other escaped spaces, and escaped
1273 // spaces or newlines in the middle of tokens?
1274 // FIXME: Add a more explicit test.
1275 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001276 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001277 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001278 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001279 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001280 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281 }
1282
1283 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001284 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001285 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001286 FormatTok.Tok.setKind(Info.getTokenID());
1287 }
1288
1289 if (FormatTok.Tok.is(tok::greatergreater)) {
1290 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001291 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001292 GreaterStashed = true;
1293 }
1294
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001295 // If we reformat comments, we remove trailing whitespace. Update the length
1296 // accordingly.
1297 if (FormatTok.Tok.is(tok::comment))
1298 FormatTok.TokenLength = Text.rtrim().size();
1299
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001300 return FormatTok;
1301 }
1302
Nico Weber29f9dea2013-02-11 15:32:15 +00001303 IdentifierTable &getIdentTable() { return IdentTable; }
1304
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001305private:
1306 FormatToken FormatTok;
1307 bool GreaterStashed;
1308 Lexer &Lex;
1309 SourceManager &SourceMgr;
1310 IdentifierTable IdentTable;
1311
1312 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001313 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001314 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1315 Tok.getLength());
1316 }
1317};
1318
Daniel Jasperf7935112012-12-03 18:12:45 +00001319class Formatter : public UnwrappedLineConsumer {
1320public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001321 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1322 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001323 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001324 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001325 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001326
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001327 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001328
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001329 tooling::Replacements format() {
1330 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1331 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1332 StructuralError = Parser.parse();
1333 unsigned PreviousEndOfLineColumn = 0;
1334 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1335 Tokens.getIdentTable().get("in"));
1336 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1337 Annotator.annotate(AnnotatedLines[i]);
1338 }
1339 deriveLocalStyle();
1340 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1341 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper0f8ed9e2013-03-13 15:53:12 +00001342
1343 // Adapt level to the next line if this is a comment.
1344 // FIXME: Can/should this be done in the UnwrappedLineParser?
1345 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1346 AnnotatedLines[i].First.Children.empty() &&
1347 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1348 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001349 }
1350 std::vector<int> IndentForLevel;
1351 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001352 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001353 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1354 E = AnnotatedLines.end();
1355 I != E; ++I) {
1356 const AnnotatedLine &TheLine = *I;
1357 const FormatToken &FirstTok = TheLine.First.FormatTok;
1358 int Offset = getIndentOffset(TheLine.First);
1359 while (IndentForLevel.size() <= TheLine.Level)
1360 IndentForLevel.push_back(-1);
1361 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001362 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001363 if (TheLine.First.is(tok::eof)) {
1364 if (PreviousLineWasTouched) {
1365 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1366 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001367 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001368 }
1369 } else if (TheLine.Type != LT_Invalid &&
1370 (WasMoved || touchesLine(TheLine))) {
1371 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1372 unsigned Indent = LevelIndent;
1373 if (static_cast<int>(Indent) + Offset >= 0)
1374 Indent += Offset;
1375 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001376 Indent = LevelIndent =
1377 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001378 } else {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001379 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1380 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001381 }
1382 tryFitMultipleLinesInOne(Indent, I, E);
1383 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1384 TheLine.First, Whitespaces,
1385 StructuralError);
1386 PreviousEndOfLineColumn =
1387 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1388 IndentForLevel[TheLine.Level] = LevelIndent;
1389 PreviousLineWasTouched = true;
1390 } else {
1391 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1392 unsigned Indent =
1393 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1394 unsigned LevelIndent = Indent;
1395 if (static_cast<int>(LevelIndent) - Offset >= 0)
1396 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001397 if (TheLine.First.isNot(tok::comment))
1398 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001399
1400 // Remove trailing whitespace of the previous line if it was touched.
1401 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001402 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1403 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001404 }
1405 // If we did not reformat this unwrapped line, the column at the end of
1406 // the last token is unchanged - thus, we can calculate the end of the
1407 // last token.
1408 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1409 PreviousEndOfLineColumn =
1410 SourceMgr.getSpellingColumnNumber(LastLoc) +
1411 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1412 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001413 if (TheLine.Last->is(tok::comment))
1414 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1415 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001416 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001417 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001418 }
1419 return Whitespaces.generateReplacements();
1420 }
1421
1422private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001423 void deriveLocalStyle() {
1424 unsigned CountBoundToVariable = 0;
1425 unsigned CountBoundToType = 0;
1426 bool HasCpp03IncompatibleFormat = false;
1427 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1428 if (AnnotatedLines[i].First.Children.empty())
1429 continue;
1430 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1431 while (!Tok->Children.empty()) {
1432 if (Tok->Type == TT_PointerOrReference) {
1433 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1434 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1435 if (SpacesBefore && !SpacesAfter)
1436 ++CountBoundToVariable;
1437 else if (!SpacesBefore && SpacesAfter)
1438 ++CountBoundToType;
1439 }
1440
Daniel Jasper400adc62013-02-08 15:28:42 +00001441 if (Tok->Type == TT_TemplateCloser &&
1442 Tok->Parent->Type == TT_TemplateCloser &&
1443 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001444 HasCpp03IncompatibleFormat = true;
1445 Tok = &Tok->Children[0];
1446 }
1447 }
1448 if (Style.DerivePointerBinding) {
1449 if (CountBoundToType > CountBoundToVariable)
1450 Style.PointerBindsToType = true;
1451 else if (CountBoundToType < CountBoundToVariable)
1452 Style.PointerBindsToType = false;
1453 }
1454 if (Style.Standard == FormatStyle::LS_Auto) {
1455 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1456 : FormatStyle::LS_Cpp03;
1457 }
1458 }
1459
Manuel Klimekb95f5452013-02-08 17:38:27 +00001460 /// \brief Get the indent of \p Level from \p IndentForLevel.
1461 ///
1462 /// \p IndentForLevel must contain the indent for the level \c l
1463 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1464 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001465 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001466 if (IndentForLevel[Level] != -1)
1467 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001468 if (Level == 0)
1469 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001470 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001471 }
1472
1473 /// \brief Get the offset of the line relatively to the level.
1474 ///
1475 /// For example, 'public:' labels in classes are offset by 1 or 2
1476 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001477 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001478 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001479 return Style.AccessModifierOffset;
1480 return 0;
1481 }
1482
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001483 /// \brief Tries to merge lines into one.
1484 ///
1485 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1486 /// if possible; note that \c I will be incremented when lines are merged.
1487 ///
1488 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001489 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001490 std::vector<AnnotatedLine>::iterator &I,
1491 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001492 // We can never merge stuff if there are trailing line comments.
1493 if (I->Last->Type == TT_LineComment)
1494 return;
1495
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001496 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001497 // If we already exceed the column limit, we set 'Limit' to 0. The different
1498 // tryMerge..() functions can then decide whether to still do merging.
1499 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001500
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001501 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001502 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001503
Daniel Jasper25837aa2013-01-14 14:14:23 +00001504 if (I->Last->is(tok::l_brace)) {
1505 tryMergeSimpleBlock(I, E, Limit);
1506 } else if (I->First.is(tok::kw_if)) {
1507 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001508 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1509 I->First.FormatTok.IsFirst)) {
1510 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001511 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001512 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001513 }
1514
Daniel Jasper39825ea2013-01-14 15:40:57 +00001515 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1516 std::vector<AnnotatedLine>::iterator E,
1517 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001518 if (Limit == 0)
1519 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001520 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001521 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1522 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001523 if (I + 2 != E && (I + 2)->InPPDirective &&
1524 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1525 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001526 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001527 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001528 join(Line, *(++I));
1529 }
1530
Daniel Jasper25837aa2013-01-14 14:14:23 +00001531 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1532 std::vector<AnnotatedLine>::iterator E,
1533 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001534 if (Limit == 0)
1535 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001536 if (!Style.AllowShortIfStatementsOnASingleLine)
1537 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001538 if ((I + 1)->InPPDirective != I->InPPDirective ||
1539 ((I + 1)->InPPDirective &&
1540 (I + 1)->First.FormatTok.HasUnescapedNewline))
1541 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001542 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001543 if (Line.Last->isNot(tok::r_paren))
1544 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001545 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001546 return;
1547 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1548 return;
1549 // Only inline simple if's (no nested if or else).
1550 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1551 return;
1552 join(Line, *(++I));
1553 }
1554
1555 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001556 std::vector<AnnotatedLine>::iterator E,
1557 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001558 // First, check that the current line allows merging. This is the case if
1559 // we're not in a control flow statement and the last token is an opening
1560 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001561 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001562 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1563 tok::kw_else, tok::kw_try, tok::kw_catch,
1564 tok::kw_for,
1565 // This gets rid of all ObjC @ keywords and methods.
1566 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001567 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001568
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001569 AnnotatedToken *Tok = &(I + 1)->First;
1570 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001571 !Tok->MustBreakBefore) {
1572 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001573 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001574 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001575 join(Line, *(I + 1));
1576 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001577 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001578 // Check that we still have three lines and they fit into the limit.
1579 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1580 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001581 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001582
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001583 // Second, check that the next line does not contain any braces - if it
1584 // does, readability declines when putting it into a single line.
1585 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1586 return;
1587 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001588 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001589 return;
1590 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1591 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001592
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001593 // Last, check that the third line contains a single closing brace.
1594 Tok = &(I + 2)->First;
1595 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1596 Tok->MustBreakBefore)
1597 return;
1598
1599 join(Line, *(I + 1));
1600 join(Line, *(I + 2));
1601 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001602 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001603 }
1604
1605 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1606 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001607 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1608 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001609 }
1610
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001611 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001612 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001613 A.Last->Children.push_back(B.First);
1614 while (!A.Last->Children.empty()) {
1615 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001616 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001617 A.Last = &A.Last->Children[0];
1618 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001619 }
1620
Daniel Jasper97b89482013-03-13 07:49:51 +00001621 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001622 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1623 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1624 Ranges[i].getBegin()) &&
1625 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1626 Range.getBegin()))
1627 return true;
1628 }
1629 return false;
1630 }
1631
1632 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001633 const FormatToken *First = &TheLine.First.FormatTok;
1634 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001635 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001636 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1637 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001638 return touchesRanges(LineRange);
1639 }
1640
1641 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1642 const FormatToken *First = &TheLine.First.FormatTok;
1643 CharSourceRange LineRange = CharSourceRange::getCharRange(
1644 First->WhiteSpaceStart,
1645 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1646 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001647 }
1648
1649 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001650 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001651 }
1652
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001653 /// \brief Add a new line and the required indent before the first Token
1654 /// of the \c UnwrappedLine if there was no structural parsing error.
1655 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001656 void formatFirstToken(const AnnotatedToken &RootToken,
1657 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001658 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001659 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001660
Daniel Jasperbbc84152013-01-29 11:27:30 +00001661 unsigned Newlines =
1662 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001663 if (Newlines == 0 && !Tok.IsFirst)
1664 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001665
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001666 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001667 // Insert extra new line before access specifiers.
1668 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1669 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1670 ++Newlines;
1671
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001672 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001673 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001674 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001675 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001676 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001677 }
1678
Alexander Kornienko116ba682013-01-14 11:34:14 +00001679 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001680 FormatStyle Style;
1681 Lexer &Lex;
1682 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001683 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001684 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001685 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001686 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001687};
1688
Daniel Jasperbbc84152013-01-29 11:27:30 +00001689tooling::Replacements
1690reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1691 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001692 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001693 OwningPtr<DiagnosticConsumer> DiagPrinter;
1694 if (DiagClient == 0) {
1695 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1696 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1697 DiagClient = DiagPrinter.get();
1698 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001699 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001700 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001701 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001702 Diagnostics.setSourceManager(&SourceMgr);
1703 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001704 return formatter.format();
1705}
1706
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001707LangOptions getFormattingLangOpts() {
1708 LangOptions LangOpts;
1709 LangOpts.CPlusPlus = 1;
1710 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001711 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001712 LangOpts.Bool = 1;
1713 LangOpts.ObjC1 = 1;
1714 LangOpts.ObjC2 = 1;
1715 return LangOpts;
1716}
1717
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001718} // namespace format
1719} // namespace clang