blob: e956f698756a36129b67d9a4069a6bc153ee9c9c [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper32d28ee2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000029#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000030#include <string>
31
Daniel Jasperbac016b2012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperbac016b2012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000051 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Daniel Jasperbac016b2012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000065 GoogleStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000067 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000068 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000069 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000070 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000071 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasperbac016b2012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000078 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000079 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
80 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000081 return ChromiumStyle;
82}
83
Daniel Jasperce3d1a62013-02-08 08:22:00 +000084// Returns the length of everything up to the first possible line break after
85// the ), ], } or > matching \c Tok.
86static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
87 if (Tok.MatchingParen == NULL)
88 return 0;
89 AnnotatedToken *End = Tok.MatchingParen;
90 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
91 End = &End->Children[0];
92 }
93 return End->TotalLength - Tok.TotalLength + 1;
94}
95
Alexander Kornienko5262dd92013-03-27 11:52:18 +000096static size_t
97calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
98 // In preprocessor directives reserve two chars for trailing " \"
99 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
100}
101
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000102/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000103///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000104/// This includes special handling for certain constructs, e.g. the alignment of
105/// trailing line comments.
106class WhitespaceManager {
107public:
Alexander Kornienko052685c2013-03-19 17:41:36 +0000108 WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
109 : SourceMgr(SourceMgr), Style(Style) {}
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000110
111 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
112 /// each \c AnnotatedToken.
113 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000114 unsigned Spaces, unsigned WhitespaceStartColumn) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000115 // 2+ newlines mean an empty line separating logic scopes.
116 if (NewLines >= 2)
117 alignComments();
118
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000119 SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
120 bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
121 Tok.FormatTok.TokenLength > Style.ColumnLimit;
122
Daniel Jasper821627e2013-01-21 22:49:20 +0000123 // Align line comments if they are trailing or if they continue other
124 // trailing comments.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000125 if (Tok.isTrailingComment()) {
Daniel Jasper812c0452013-03-01 16:45:59 +0000126 // Remove the comment's trailing whitespace.
127 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
128 Replaces.insert(tooling::Replacement(
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000129 SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
Daniel Jasper812c0452013-03-01 16:45:59 +0000130 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
131
132 // Align comment with other comments.
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000133 if ((Tok.Parent != NULL || !Comments.empty()) &&
134 !LineExceedsColumnLimit) {
135 StoredComment Comment;
136 Comment.Tok = Tok.FormatTok;
137 Comment.Spaces = Spaces;
138 Comment.NewLines = NewLines;
139 Comment.MinColumn =
140 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
141 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
142 Comment.Untouchable = false;
143 Comments.push_back(Comment);
144 return;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000145 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000146 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000147
148 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000149 if (Tok.Children.empty() && !Tok.isTrailingComment())
Daniel Jasper821627e2013-01-21 22:49:20 +0000150 alignComments();
Alexander Kornienkof7536152013-03-14 16:10:54 +0000151
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000152 if (Tok.Type == TT_BlockComment) {
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000153 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000154 } else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
155 StringRef Line(SourceMgr.getCharacterData(TokenLoc),
156 Tok.FormatTok.TokenLength);
157 int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
158 StringRef Prefix = getLineCommentPrefix(Line);
159 std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
160 splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
161 StartColumn + Prefix.size(), NewPrefix,
162 /*InPPDirective=*/ false,
163 /*CommentHasMoreLines=*/ false);
164 }
Alexander Kornienkof7536152013-03-14 16:10:54 +0000165
Manuel Klimek8092a942013-02-20 10:15:13 +0000166 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000167 }
168
169 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
170 /// backslashes to escape newlines inside a preprocessor directive.
171 ///
172 /// This function and \c replaceWhitespace have the same behavior if
173 /// \c Newlines == 0.
174 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000175 unsigned Spaces, unsigned WhitespaceStartColumn) {
176 if (Tok.Type == TT_BlockComment)
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000177 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000178
179 storeReplacement(Tok.FormatTok,
180 getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
Manuel Klimek8092a942013-02-20 10:15:13 +0000181 }
182
183 /// \brief Inserts a line break into the middle of a token.
184 ///
185 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
186 /// break and \p Postfix before the rest of the token starts in the next line.
187 ///
188 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
189 /// used to generate the correct line break.
Alexander Kornienko052685c2013-03-19 17:41:36 +0000190 void breakToken(const FormatToken &Tok, unsigned Offset,
191 unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
192 bool InPPDirective, unsigned Spaces,
193 unsigned WhitespaceStartColumn) {
Manuel Klimek8092a942013-02-20 10:15:13 +0000194 std::string NewLineText;
195 if (!InPPDirective)
196 NewLineText = getNewLineText(1, Spaces);
197 else
Alexander Kornienko052685c2013-03-19 17:41:36 +0000198 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
Manuel Klimek8092a942013-02-20 10:15:13 +0000199 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
Alexander Kornienko052685c2013-03-19 17:41:36 +0000200 SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
201 Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
202 ReplacementText));
Manuel Klimek8092a942013-02-20 10:15:13 +0000203 }
204
205 /// \brief Returns all the \c Replacements created during formatting.
206 const tooling::Replacements &generateReplacements() {
207 alignComments();
208 return Replaces;
209 }
210
Daniel Jasperc363dbb2013-03-22 16:25:51 +0000211 void addUntouchableComment(unsigned Column) {
212 StoredComment Comment;
213 Comment.MinColumn = Column;
214 Comment.MaxColumn = Column;
215 Comment.Untouchable = true;
216 Comments.push_back(Comment);
217 }
218
Manuel Klimek8092a942013-02-20 10:15:13 +0000219private:
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000220 static StringRef getLineCommentPrefix(StringRef Comment) {
221 const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
222 for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
223 if (Comment.startswith(KnownPrefixes[i]))
224 return KnownPrefixes[i];
225 return "";
226 }
227
Alexander Kornienko052685c2013-03-19 17:41:36 +0000228 /// \brief Finds a common prefix of lines of a block comment to properly
229 /// indent (and possibly decorate with '*'s) added lines.
230 ///
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000231 /// The first line is ignored (it's special and starts with /*). The number of
232 /// lines should be more than one.
Alexander Kornienko052685c2013-03-19 17:41:36 +0000233 static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
234 const char *PrefixChars = " *") {
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000235 assert(Lines.size() > 1);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000236 StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
237 for (size_t i = 2; i < Lines.size(); ++i) {
238 for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
239 if (Prefix[j] != Lines[i][j]) {
240 Prefix = Prefix.substr(0, j);
241 break;
242 }
243 }
244 }
245 return Prefix;
246 }
247
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000248 /// \brief Splits one line in a line or block comment, if it doesn't fit to
249 /// provided column limit. Removes trailing whitespace in each line.
250 ///
251 /// \param Line points to the line contents without leading // or /*.
252 ///
253 /// \param StartColumn is the column where the first character of Line will be
254 /// located after formatting.
255 ///
256 /// \param LinePrefix is inserted after each line break.
257 ///
258 /// When \param InPPDirective is true, each line break will be preceded by a
259 /// backslash in the last column to make line breaks inside the comment
260 /// visually consistent with line breaks outside the comment. This only makes
261 /// sense for block comments.
262 ///
263 /// When \param CommentHasMoreLines is false, no line breaks/trailing
264 /// backslashes will be inserted after it.
Alexander Kornienko052685c2013-03-19 17:41:36 +0000265 void splitLineInComment(const FormatToken &Tok, StringRef Line,
266 size_t StartColumn, StringRef LinePrefix,
267 bool InPPDirective, bool CommentHasMoreLines,
268 const char *WhiteSpaceChars = " ") {
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000269 size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000270 const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000271
272 StringRef TrimmedLine = Line.rtrim();
273 int TrailingSpaceLength = Line.size() - TrimmedLine.size();
274
275 // Don't touch leading whitespace.
276 Line = TrimmedLine.ltrim();
277 StartColumn += TrimmedLine.size() - Line.size();
278
279 while (Line.size() + StartColumn > ColumnLimit) {
Alexander Kornienko052685c2013-03-19 17:41:36 +0000280 // Try to break at the last whitespace before the column limit.
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000281 size_t SpacePos =
282 Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000283 if (SpacePos == StringRef::npos) {
284 // Try to find any whitespace in the line.
285 SpacePos = Line.find_first_of(WhiteSpaceChars);
286 if (SpacePos == StringRef::npos) // No whitespace found, give up.
287 break;
288 }
289
290 StringRef NextCut = Line.substr(0, SpacePos).rtrim();
291 StringRef RemainingLine = Line.substr(SpacePos).ltrim();
292 if (RemainingLine.empty())
293 break;
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000294
295 if (RemainingLine == "*/" && LinePrefix.endswith("* "))
296 LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
297
Alexander Kornienko052685c2013-03-19 17:41:36 +0000298 Line = RemainingLine;
299
300 size_t ReplaceChars = Line.begin() - NextCut.end();
301 breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000302 InPPDirective, 0, NextCut.size() + StartColumn);
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000303 StartColumn = LinePrefix.size();
Alexander Kornienko052685c2013-03-19 17:41:36 +0000304 }
305
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000306 if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
307 // Remove trailing whitespace/insert backslash. + 1 is for \n
308 breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
309 InPPDirective, 0, Line.size() + StartColumn);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000310 }
311 }
312
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000313 /// \brief Changes indentation of all lines in a block comment by Indent,
314 /// removes trailing whitespace from each line, splits lines that end up
315 /// exceeding the column limit.
Alexander Kornienko052685c2013-03-19 17:41:36 +0000316 void indentBlockComment(const AnnotatedToken &Tok, int Indent,
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000317 int WhitespaceStartColumn, int NewLines,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000318 bool InPPDirective) {
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000319 assert(Tok.Type == TT_BlockComment);
320 int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000321 const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
322 const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
323 const int IndentDelta = Indent - CurrentIndent;
324 const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
325 Tok.FormatTok.TokenLength);
326 assert(Text.startswith("/*") && Text.endswith("*/"));
327
328 SmallVector<StringRef, 16> Lines;
329 Text.split(Lines, "\n");
330
331 if (IndentDelta > 0) {
332 std::string WhiteSpace(IndentDelta, ' ');
333 for (size_t i = 1; i < Lines.size(); ++i) {
334 Replaces.insert(tooling::Replacement(
335 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
336 0, WhiteSpace));
337 }
338 } else if (IndentDelta < 0) {
339 std::string WhiteSpace(-IndentDelta, ' ');
340 // Check that the line is indented enough.
341 for (size_t i = 1; i < Lines.size(); ++i) {
342 if (!Lines[i].startswith(WhiteSpace))
343 return;
344 }
345 for (size_t i = 1; i < Lines.size(); ++i) {
346 Replaces.insert(tooling::Replacement(
347 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
348 -IndentDelta, ""));
Alexander Kornienkof7536152013-03-14 16:10:54 +0000349 }
350 }
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000351
Alexander Kornienko052685c2013-03-19 17:41:36 +0000352 // Split long lines in comments.
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000353 size_t OldPrefixSize = 0;
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000354 std::string NewPrefix;
355 if (Lines.size() > 1) {
356 StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000357 OldPrefixSize = CurrentPrefix.size();
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000358 NewPrefix = (IndentDelta < 0)
359 ? CurrentPrefix.substr(-IndentDelta).str()
360 : std::string(IndentDelta, ' ') + CurrentPrefix.str();
361 if (CurrentPrefix.endswith("*")) {
362 NewPrefix += " ";
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000363 ++OldPrefixSize;
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000364 }
365 } else if (Tok.Parent == 0) {
366 NewPrefix = std::string(StartColumn, ' ') + " * ";
Alexander Kornienko052685c2013-03-19 17:41:36 +0000367 }
368
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000369 StartColumn += 2;
Alexander Kornienko052685c2013-03-19 17:41:36 +0000370 for (size_t i = 0; i < Lines.size(); ++i) {
Alexander Kornienko5262dd92013-03-27 11:52:18 +0000371 StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
Alexander Kornienko052685c2013-03-19 17:41:36 +0000372 splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
373 InPPDirective, i != Lines.size() - 1);
Alexander Kornienko7c22cf32013-03-21 12:28:10 +0000374 StartColumn = NewPrefix.size();
Alexander Kornienko1fdd8b32013-03-15 13:42:02 +0000375 }
Alexander Kornienkof7536152013-03-14 16:10:54 +0000376 }
377
Manuel Klimek8092a942013-02-20 10:15:13 +0000378 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
379 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
380 }
381
Alexander Kornienko052685c2013-03-19 17:41:36 +0000382 std::string getNewLineText(unsigned NewLines, unsigned Spaces,
383 unsigned WhitespaceStartColumn) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000384 std::string NewLineText;
385 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000386 unsigned Offset =
387 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000388 for (unsigned i = 0; i < NewLines; ++i) {
389 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
390 NewLineText += "\\\n";
391 Offset = 0;
392 }
393 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000394 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000395 }
396
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000397 /// \brief Structure to store a comment for later layout and alignment.
398 struct StoredComment {
399 FormatToken Tok;
400 unsigned MinColumn;
401 unsigned MaxColumn;
402 unsigned NewLines;
403 unsigned Spaces;
Daniel Jasperc363dbb2013-03-22 16:25:51 +0000404 bool Untouchable;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000405 };
406 SmallVector<StoredComment, 16> Comments;
407 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
408
409 /// \brief Try to align all stashed comments.
410 void alignComments() {
411 unsigned MinColumn = 0;
412 unsigned MaxColumn = UINT_MAX;
413 comment_iterator Start = Comments.begin();
Alexander Kornienkof7536152013-03-14 16:10:54 +0000414 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000415 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
416 alignComments(Start, I, MinColumn);
417 MinColumn = I->MinColumn;
418 MaxColumn = I->MaxColumn;
419 Start = I;
420 } else {
421 MinColumn = std::max(MinColumn, I->MinColumn);
422 MaxColumn = std::min(MaxColumn, I->MaxColumn);
423 }
424 }
425 alignComments(Start, Comments.end(), MinColumn);
426 Comments.clear();
427 }
428
429 /// \brief Put all the comments between \p I and \p E into \p Column.
430 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
431 while (I != E) {
Daniel Jasperc363dbb2013-03-22 16:25:51 +0000432 if (!I->Untouchable) {
433 unsigned Spaces = I->Spaces + Column - I->MinColumn;
Alexander Kornienko94b748f2013-03-27 17:08:02 +0000434 storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
Daniel Jasperc363dbb2013-03-22 16:25:51 +0000435 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000436 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000437 }
438 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000439
440 /// \brief Stores \p Text as the replacement for the whitespace in front of
441 /// \p Tok.
442 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000443 // Don't create a replacement, if it does not change anything.
444 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
445 Tok.WhiteSpaceLength) == Text)
446 return;
447
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000448 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
449 Tok.WhiteSpaceLength, Text));
450 }
451
452 SourceManager &SourceMgr;
453 tooling::Replacements Replaces;
Alexander Kornienko052685c2013-03-19 17:41:36 +0000454 const FormatStyle &Style;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000455};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000456
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457class UnwrappedLineFormatter {
458public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000459 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000460 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000461 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000462 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000463 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000464 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000465 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000466
Manuel Klimekd4397b92013-01-04 23:34:14 +0000467 /// \brief Formats an \c UnwrappedLine.
468 ///
469 /// \returns The column after the last token in the last line of the
470 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000471 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000472 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000473 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000474 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000475 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000476 State.Stack.push_back(
Daniel Jasper37911302013-04-02 14:33:13 +0000477 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper6f21a982013-03-13 07:49:51 +0000478 /*HasMultiParameterLine=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000479 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000480 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000481 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000482 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000483
484 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000485 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000486
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000487 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000488 unsigned ColumnLimit = Style.ColumnLimit;
489 if (NextLine && NextLine->InPPDirective &&
490 !NextLine->First.FormatTok.HasUnescapedNewline)
491 ColumnLimit = getColumnLimit();
492 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000493 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000494 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000495 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000496 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000497 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000498
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000499 // If the ObjC method declaration does not fit on a line, we should format
500 // it with one arg per line.
501 if (Line.Type == LT_ObjCMethodDecl)
502 State.Stack.back().BreakBeforeParameter = true;
503
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000504 // Find best solution in solution space.
505 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000506 }
507
508private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000509 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
510 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000511 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
512 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000513 llvm::errs();
514 }
515
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000516 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000517 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
518 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000519 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
520 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000521 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper24849712013-03-01 16:48:32 +0000522 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasper37911302013-04-02 14:33:13 +0000523 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000524 CallContinuation(0), VariablePos(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000525
Daniel Jasperbac016b2012-12-03 18:12:45 +0000526 /// \brief The position to which a specific parenthesis level needs to be
527 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000528 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000529
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000530 /// \brief The position of the last space on each level.
531 ///
532 /// Used e.g. to break like:
533 /// functionCall(Parameter, otherCall(
534 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000535 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000536
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000537 /// \brief The position the first "<<" operator encountered on each level.
538 ///
539 /// Used to align "<<" operators. 0 if no such operator has been encountered
540 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000541 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000542
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000543 /// \brief Whether a newline needs to be inserted before the block's closing
544 /// brace.
545 ///
546 /// We only want to insert a newline before the closing brace if there also
547 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000548 bool BreakBeforeClosingBrace;
549
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000550 /// \brief The column of a \c ? in a conditional expression;
551 unsigned QuestionColumn;
552
Daniel Jasperf343cab2013-01-31 14:59:26 +0000553 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
554 /// lines, in this context.
555 bool AvoidBinPacking;
556
557 /// \brief Break after the next comma (or all the commas in this context if
558 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000559 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000560
561 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000562 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000563
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000564 /// \brief The position of the colon in an ObjC method declaration/call.
565 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000566
Daniel Jasper24849712013-03-01 16:48:32 +0000567 /// \brief The start of the most recent function in a builder-type call.
568 unsigned StartOfFunctionCall;
569
Daniel Jasper37911302013-04-02 14:33:13 +0000570 /// \brief If a nested name specifier was broken over multiple lines, this
571 /// contains the start column of the second line. Otherwise 0.
572 unsigned NestedNameSpecifierContinuation;
573
574 /// \brief If a call expression was broken over multiple lines, this
575 /// contains the start column of the second line. Otherwise 0.
576 unsigned CallContinuation;
577
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000578 /// \brief The column of the first variable name in a variable declaration.
579 ///
580 /// Used to align further variables if necessary.
581 unsigned VariablePos;
582
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000583 bool operator<(const ParenState &Other) const {
584 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000585 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000586 if (LastSpace != Other.LastSpace)
587 return LastSpace < Other.LastSpace;
588 if (FirstLessLess != Other.FirstLessLess)
589 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000590 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
591 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000592 if (QuestionColumn != Other.QuestionColumn)
593 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000594 if (AvoidBinPacking != Other.AvoidBinPacking)
595 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000596 if (BreakBeforeParameter != Other.BreakBeforeParameter)
597 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000598 if (HasMultiParameterLine != Other.HasMultiParameterLine)
599 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000600 if (ColonPos != Other.ColonPos)
601 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000602 if (StartOfFunctionCall != Other.StartOfFunctionCall)
603 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000604 if (NestedNameSpecifierContinuation !=
605 Other.NestedNameSpecifierContinuation)
606 return NestedNameSpecifierContinuation <
607 Other.NestedNameSpecifierContinuation;
608 if (CallContinuation != Other.CallContinuation)
609 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000610 if (VariablePos != Other.VariablePos)
611 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000612 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000613 }
614 };
615
616 /// \brief The current state when indenting a unwrapped line.
617 ///
618 /// As the indenting tries different combinations this is copied by value.
619 struct LineState {
620 /// \brief The number of used columns in the current line.
621 unsigned Column;
622
623 /// \brief The token that needs to be next formatted.
624 const AnnotatedToken *NextToken;
625
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000626 /// \brief \c true if this line contains a continued for-loop section.
627 bool LineContainsContinuedForLoopSection;
628
Daniel Jasper29f123b2013-02-08 15:28:42 +0000629 /// \brief The level of nesting inside (), [], <> and {}.
630 unsigned ParenLevel;
631
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000632 /// \brief The \c ParenLevel at the start of this line.
633 unsigned StartOfLineLevel;
634
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000635 /// \brief The start column of the string literal, if we're in a string
636 /// literal sequence, 0 otherwise.
637 unsigned StartOfStringLiteral;
638
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000639 /// \brief A stack keeping track of properties applying to parenthesis
640 /// levels.
641 std::vector<ParenState> Stack;
642
643 /// \brief Comparison operator to be able to used \c LineState in \c map.
644 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000645 if (NextToken != Other.NextToken)
646 return NextToken < Other.NextToken;
647 if (Column != Other.Column)
648 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000649 if (LineContainsContinuedForLoopSection !=
Daniel Jasperf9955d32013-03-20 12:37:50 +0000650 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000651 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000652 if (ParenLevel != Other.ParenLevel)
653 return ParenLevel < Other.ParenLevel;
654 if (StartOfLineLevel != Other.StartOfLineLevel)
655 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000656 if (StartOfStringLiteral != Other.StartOfStringLiteral)
657 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000658 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000659 }
660 };
661
Daniel Jasper20409152012-12-04 14:54:30 +0000662 /// \brief Appends the next token to \p State and updates information
663 /// necessary for indentation.
664 ///
665 /// Puts the token on the current line if \p Newline is \c true and adds a
666 /// line break and necessary indentation otherwise.
667 ///
668 /// If \p DryRun is \c false, also creates and stores the required
669 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000670 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000671 const AnnotatedToken &Current = *State.NextToken;
672 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000673
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000674 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000675 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
676 State.NextToken->FormatTok.TokenLength;
677 if (State.NextToken->Children.empty())
678 State.NextToken = NULL;
679 else
680 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000681 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000682 }
683
Daniel Jasper3776ef32013-04-03 07:21:51 +0000684 // If we are continuing an expression, we want to indent an extra 4 spaces.
685 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000686 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000687 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000688 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000689 if (Current.is(tok::r_brace)) {
690 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000691 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000692 State.StartOfStringLiteral != 0) {
693 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000694 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000695 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000696 State.Stack.back().FirstLessLess != 0) {
697 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper37911302013-04-02 14:33:13 +0000698 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000699 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
700 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000701 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000702 } else {
703 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
704 }
Daniel Jasper37911302013-04-02 14:33:13 +0000705 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000706 if (State.Stack.back().CallContinuation == 0) {
707 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000708 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000709 } else {
710 State.Column = State.Stack.back().CallContinuation;
711 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000712 } else if (Current.Type == TT_ConditionalExpr) {
713 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000714 } else if (Previous.is(tok::comma) &&
715 State.Stack.back().VariablePos != 0) {
716 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000717 } else if (Previous.ClosesTemplateDeclaration ||
718 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000719 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000720 } else if (Current.Type == TT_ObjCSelectorName) {
721 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
722 State.Column =
723 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
724 } else {
725 State.Column = State.Stack.back().Indent;
726 State.Stack.back().ColonPos =
727 State.Column + Current.FormatTok.TokenLength;
728 }
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000729 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000730 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000731 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000732 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000733 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000734 // Ensure that we fall back to indenting 4 spaces instead of just
735 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000736 if (State.Column == FirstIndent)
737 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000738 }
739
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000740 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000741 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000742 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jasper237d4c12013-02-23 21:01:55 +0000743 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000744 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000745
Manuel Klimek060143e2013-01-02 18:33:23 +0000746 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000747 unsigned NewLines = 1;
748 if (Current.Type == TT_LineComment)
749 NewLines =
750 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
751 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000752 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000753 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000754 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000755 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000756 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000757 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000758 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000759
Daniel Jasper29f123b2013-02-08 15:28:42 +0000760 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000761 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000762
763 // Any break on this level means that the parent level has been broken
764 // and we need to avoid bin packing there.
765 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
766 State.Stack[i].BreakBeforeParameter = true;
767 }
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000768 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000769 State.Stack.back().BreakBeforeParameter = true;
770
Daniel Jasper237d4c12013-02-23 21:01:55 +0000771 // If we break after {, we should also break before the corresponding }.
772 if (Previous.is(tok::l_brace))
773 State.Stack.back().BreakBeforeClosingBrace = true;
774
775 if (State.Stack.back().AvoidBinPacking) {
776 // If we are breaking after '(', '{', '<', this is not bin packing
777 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000778 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000779 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
780 Line.MustBeDeclaration))
781 State.Stack.back().BreakBeforeParameter = true;
782 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000784 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000785 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
786 State.Stack.back().VariablePos == 0) {
787 State.Stack.back().VariablePos = State.Column;
788 // Move over * and & if they are bound to the variable name.
789 const AnnotatedToken *Tok = &Previous;
790 while (Tok &&
791 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
792 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
793 if (Tok->SpacesRequiredBefore != 0)
794 break;
795 Tok = Tok->Parent;
796 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000797 if (Previous.PartOfMultiVariableDeclStmt)
798 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
799 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000800
Daniel Jasper729a7432013-02-11 12:36:37 +0000801 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000802
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 if (!DryRun)
Alexander Kornienko052685c2013-03-19 17:41:36 +0000804 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper20409152012-12-04 14:54:30 +0000805
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000806 if (Current.Type == TT_ObjCSelectorName &&
807 State.Stack.back().ColonPos == 0) {
808 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperf9955d32013-03-20 12:37:50 +0000809 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000810 State.Stack.back().ColonPos =
811 State.Stack.back().Indent + Current.LongestObjCSelectorName;
812 else
813 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000814 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000815 }
816
Daniel Jasperac3223e2013-04-10 09:49:49 +0000817 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000818 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000819 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000820 if (Previous.is(tok::comma) && !Current.isTrailingComment())
Daniel Jasper29f123b2013-02-08 15:28:42 +0000821 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000822
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000823 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000824 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000825 // Treat the condition inside an if as if it was a second function
826 // parameter, i.e. let nested calls have an indent of 4.
827 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000828 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000829 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000830 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000831 Previous.Type == TT_ConditionalExpr ||
832 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000833 getPrecedence(Previous) != prec::Assignment)
834 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000835 else if (Previous.Type == TT_InheritanceColon)
836 State.Stack.back().Indent = State.Column;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000837 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper986e17f2013-01-28 07:35:34 +0000838 // If this function has multiple parameters, indent nested calls from
839 // the start of the first parameter.
840 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000841 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000842
Manuel Klimek8092a942013-02-20 10:15:13 +0000843 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000844 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000845
Daniel Jasper20409152012-12-04 14:54:30 +0000846 /// \brief Mark the next token as consumed in \p State and modify its stacks
847 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000848 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000849 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000850 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000851
Daniel Jasper6cabab42013-02-14 08:42:54 +0000852 if (Current.Type == TT_InheritanceColon)
853 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000854 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
855 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000856 if (Current.is(tok::question))
857 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000858 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000859 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
860 State.Stack.back().StartOfFunctionCall =
861 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000862 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000863 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000864 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
865 State.Stack.back().AvoidBinPacking = true;
866 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000867 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000868
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000869 // If return returns a binary expression, align after it.
870 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
871 State.Stack.back().LastSpace = State.Column + 7;
872
Daniel Jasper3776ef32013-04-03 07:21:51 +0000873 // In ObjC method declaration we align on the ":" of parameters, but we need
874 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000875 if (Current.Type == TT_ObjCMethodSpecifier)
876 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000877
Daniel Jasper29f123b2013-02-08 15:28:42 +0000878 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000879 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
880 // Don't add extra indentation for the first fake parenthesis after
881 // 'return', assignements or opening <({[. The indentation for these cases
882 // is special cased.
883 bool SkipFirstExtraIndent =
884 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000885 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000886 getPrecedence(*Previous) == prec::Assignment));
887 for (SmallVector<prec::Level, 4>::const_reverse_iterator
888 I = Current.FakeLParens.rbegin(),
889 E = Current.FakeLParens.rend();
890 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000891 ParenState NewParenState = State.Stack.back();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000892 NewParenState.Indent =
893 std::max(std::max(State.Column, NewParenState.Indent),
894 State.Stack.back().LastSpace);
895
896 // Always indent conditional expressions. Never indent expression where
897 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
898 // prec::Assignment) as those have different indentation rules. Indent
899 // other expression, unless the indentation needs to be skipped.
900 if (*I == prec::Conditional ||
901 (!SkipFirstExtraIndent && *I > prec::Assignment))
902 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000903 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000904 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000905 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000906 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000907 }
908
Daniel Jaspercf225b62012-12-24 13:43:52 +0000909 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000910 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000911 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000912 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000913 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000914 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000915 NewIndent = 2 + State.Stack.back().LastSpace;
916 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000917 } else {
Daniel Jasper24849712013-03-01 16:48:32 +0000918 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
919 State.Stack.back().StartOfFunctionCall);
Daniel Jasper3a39ac72013-02-28 09:39:12 +0000920 AvoidBinPacking =
921 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000922 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000923 State.Stack.push_back(
924 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
925 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000926 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000927 }
928
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000929 // If this '[' opens an ObjC call, determine whether all parameters fit into
930 // one line and put one per line if they don't.
931 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
932 Current.MatchingParen != NULL) {
933 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
934 State.Stack.back().BreakBeforeParameter = true;
935 }
936
Daniel Jaspercf225b62012-12-24 13:43:52 +0000937 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000938 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000939 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000940 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
941 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000942 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000943 --State.ParenLevel;
944 }
945
946 // Remove scopes created by fake parenthesis.
947 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000948 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000949 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000950 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000951 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000952
Manuel Klimeke9a62262013-02-20 15:32:58 +0000953 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000954 State.StartOfStringLiteral = State.Column;
955 } else if (Current.isNot(tok::comment)) {
956 State.StartOfStringLiteral = 0;
957 }
958
Manuel Klimek8092a942013-02-20 10:15:13 +0000959 State.Column += Current.FormatTok.TokenLength;
960
Daniel Jasper26f7e782013-01-08 14:56:18 +0000961 if (State.NextToken->Children.empty())
962 State.NextToken = NULL;
963 else
964 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000965
Manuel Klimek8092a942013-02-20 10:15:13 +0000966 return breakProtrudingToken(Current, State, DryRun);
967 }
968
969 /// \brief If the current token sticks out over the end of the line, break
970 /// it if possible.
971 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
972 bool DryRun) {
973 if (Current.isNot(tok::string_literal))
974 return 0;
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000975 // Only break up default narrow strings.
Alexander Kornienko052685c2013-03-19 17:41:36 +0000976 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
977 if (!LiteralData || *LiteralData != '"')
Manuel Klimekaa62d0c2013-03-08 18:59:48 +0000978 return 0;
Manuel Klimek8092a942013-02-20 10:15:13 +0000979
980 unsigned Penalty = 0;
981 unsigned TailOffset = 0;
982 unsigned TailLength = Current.FormatTok.TokenLength;
983 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
984 unsigned OffsetFromStart = 0;
985 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienko052685c2013-03-19 17:41:36 +0000986 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimekbc30c712013-03-01 13:29:19 +0000987 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000988 break;
Manuel Klimekbc30c712013-03-01 13:29:19 +0000989 StringRef::size_type SplitPoint = getSplitPoint(
990 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek8092a942013-02-20 10:15:13 +0000991 if (SplitPoint == StringRef::npos)
992 break;
993 assert(SplitPoint != 0);
994 // +2, because 'Text' starts after the opening quotes, and does not
995 // include the closing quote we need to insert.
996 unsigned WhitespaceStartColumn =
997 StartColumn + OffsetFromStart + SplitPoint + 2;
998 State.Stack.back().LastSpace = StartColumn;
999 if (!DryRun) {
Alexander Kornienko052685c2013-03-19 17:41:36 +00001000 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
1001 0, "\"", "\"", Line.InPPDirective, StartColumn,
1002 WhitespaceStartColumn);
Manuel Klimek8092a942013-02-20 10:15:13 +00001003 }
1004 TailOffset += SplitPoint + 1;
1005 TailLength -= SplitPoint + 1;
1006 OffsetFromStart = 1;
Daniel Jasper0fb382b2013-02-26 12:52:34 +00001007 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasperfaab0d32013-02-27 09:47:53 +00001008 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1009 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek8092a942013-02-20 10:15:13 +00001010 }
1011 State.Column = StartColumn + TailLength;
1012 return Penalty;
1013 }
1014
1015 StringRef::size_type
1016 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekaf31fd72013-03-01 13:14:08 +00001017 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +00001018 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +00001019 return SpaceOffset;
1020 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +00001021 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +00001022 return SlashOffset;
Manuel Klimekaa62d0c2013-03-08 18:59:48 +00001023 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
1024 if (Split != StringRef::npos && Split > 1)
Manuel Klimekbc30c712013-03-01 13:29:19 +00001025 // Do not split at 0.
Manuel Klimekaa62d0c2013-03-08 18:59:48 +00001026 return Split - 1;
Manuel Klimekbc30c712013-03-01 13:29:19 +00001027 return StringRef::npos;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001028 }
1029
Manuel Klimekaa62d0c2013-03-08 18:59:48 +00001030 StringRef::size_type
1031 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
1032 StringRef::size_type NextEscape = Text.find('\\');
1033 while (NextEscape != StringRef::npos && NextEscape < Offset) {
1034 StringRef::size_type SequenceLength =
1035 getEscapeSequenceLength(Text.substr(NextEscape));
1036 if (Offset < NextEscape + SequenceLength)
1037 return NextEscape;
1038 NextEscape = Text.find('\\', NextEscape + SequenceLength);
1039 }
1040 return Offset;
1041 }
1042
1043 unsigned getEscapeSequenceLength(StringRef Text) {
1044 assert(Text[0] == '\\');
1045 if (Text.size() < 2)
1046 return 1;
1047
1048 switch (Text[1]) {
1049 case 'u':
1050 return 6;
1051 case 'U':
1052 return 10;
1053 case 'x':
1054 return getHexLength(Text);
1055 default:
1056 if (Text[1] >= '0' && Text[1] <= '7')
1057 return getOctalLength(Text);
1058 return 2;
1059 }
1060 }
1061
1062 unsigned getHexLength(StringRef Text) {
1063 unsigned I = 2; // Point after '\x'.
1064 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
1065 (Text[I] >= 'a' && Text[I] <= 'f') ||
1066 (Text[I] >= 'A' && Text[I] <= 'F'))) {
1067 ++I;
1068 }
1069 return I;
1070 }
1071
1072 unsigned getOctalLength(StringRef Text) {
1073 unsigned I = 1;
1074 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
1075 ++I;
1076 }
1077 return I;
1078 }
1079
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001080 unsigned getColumnLimit() {
Alexander Kornienko5262dd92013-03-27 11:52:18 +00001081 return calculateColumnLimit(Style, Line.InPPDirective);
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001082 }
1083
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001084 /// \brief An edge in the solution space from \c Previous->State to \c State,
1085 /// inserting a newline dependent on the \c NewLine.
1086 struct StateNode {
1087 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +00001088 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001089 LineState State;
1090 bool NewLine;
1091 StateNode *Previous;
1092 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001093
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001094 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1095 ///
1096 /// In case of equal penalties, we want to prefer states that were inserted
1097 /// first. During state generation we make sure that we insert states first
1098 /// that break the line as late as possible.
1099 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1100
1101 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1102 /// \c State has the given \c OrderedPenalty.
1103 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1104
1105 /// \brief The BFS queue type.
1106 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1107 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001108
1109 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001110 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001111 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1112 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1113 /// find the shortest path (the one with lowest penalty) from \p InitialState
1114 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001115 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001116 std::set<LineState> Seen;
1117
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001118 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +00001119 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001120 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1121 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1122 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001123
1124 // While not empty, take first element and follow edges.
1125 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001126 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +00001127 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001128 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +00001129 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001130 break;
Daniel Jasper01786732013-02-04 07:21:18 +00001131 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001132 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001133
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001134 if (!Seen.insert(Node->State).second)
1135 // State already examined with lower penalty.
1136 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001137
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001138 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1139 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001140 }
1141
1142 if (Queue.empty())
1143 // We were unable to find a solution, do nothing.
1144 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +00001145 return 0;
1146
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001147 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001148 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +00001149 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001151 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001152 return Queue.top().second->State.Column;
1153 }
1154
1155 void reconstructPath(LineState &State, StateNode *Current) {
1156 // FIXME: This recursive implementation limits the possible number
1157 // of tokens per line if compiled into a binary with small stack space.
1158 // To become more independent of stack frame limitations we would need
1159 // to also change the TokenAnnotator.
1160 if (Current->Previous == NULL)
1161 return;
1162 reconstructPath(State, Current->Previous);
1163 DEBUG({
1164 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +00001165 llvm::errs()
1166 << "Penalty for splitting before "
1167 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1168 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001169 }
1170 });
1171 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001172 }
1173
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001174 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001175 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001176 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001177 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001178 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1179 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001180 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001181 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001182 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001183 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +00001184 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001185 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1186
1187 StateNode *Node = new (Allocator.Allocate())
1188 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +00001189 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001190 if (Node->State.Column > getColumnLimit()) {
1191 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +00001192 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +00001193 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +00001194
1195 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1196 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001197 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001198
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001199 /// \brief Returns \c true, if a line break after \p State is allowed.
1200 bool canBreak(const LineState &State) {
1201 if (!State.NextToken->CanBreakBefore &&
1202 !(State.NextToken->is(tok::r_brace) &&
1203 State.Stack.back().BreakBeforeClosingBrace))
1204 return false;
1205 // Trying to insert a parameter on a new line if there are already more than
1206 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +00001207 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001208 State.Stack.back().AvoidBinPacking)
1209 return false;
1210 return true;
1211 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001212
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001213 /// \brief Returns \c true, if a line break after \p State is mandatory.
1214 bool mustBreak(const LineState &State) {
1215 if (State.NextToken->MustBreakBefore)
1216 return true;
1217 if (State.NextToken->is(tok::r_brace) &&
1218 State.Stack.back().BreakBeforeClosingBrace)
1219 return true;
1220 if (State.NextToken->Parent->is(tok::semi) &&
1221 State.LineContainsContinuedForLoopSection)
1222 return true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001223 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +00001224 State.NextToken->is(tok::question) ||
1225 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001226 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperac3223e2013-04-10 09:49:49 +00001227 !State.NextToken->isTrailingComment() &&
Daniel Jasper7d812812013-02-21 15:00:29 +00001228 State.NextToken->isNot(tok::r_paren) &&
1229 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001230 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001231 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1232 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001233 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +00001234 State.NextToken->LongestObjCSelectorName == 0 &&
1235 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +00001236 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001237 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1238 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +00001239 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001240 return true;
Daniel Jasper923ebef2013-03-14 13:45:21 +00001241 if (State.NextToken->Type == TT_InlineASMColon)
1242 return true;
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001243 // This prevents breaks like:
1244 // ...
1245 // SomeParameter, OtherParameter).DoSomething(
1246 // ...
1247 // As they hide "DoSomething" and generally bad for readability.
1248 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1249 getRemainingLength(State) + State.Column > getColumnLimit() &&
1250 State.ParenLevel < State.StartOfLineLevel)
1251 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +00001252 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001253 }
1254
Daniel Jasper3af59ce2013-03-15 14:57:30 +00001255 // Returns the total number of columns required for the remaining tokens.
1256 unsigned getRemainingLength(const LineState &State) {
1257 if (State.NextToken && State.NextToken->Parent)
1258 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1259 return 0;
1260 }
1261
Daniel Jasperbac016b2012-12-03 18:12:45 +00001262 FormatStyle Style;
1263 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +00001264 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001265 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001266 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001267 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +00001268
1269 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1270 QueueType Queue;
1271 // Increasing count of \c StateNode items we have created. This is used
1272 // to create a deterministic order independent of the container.
1273 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001274};
1275
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001276class LexerBasedFormatTokenSource : public FormatTokenSource {
1277public:
1278 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001279 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001280 IdentTable(Lex.getLangOpts()) {
1281 Lex.SetKeepWhitespaceMode(true);
1282 }
1283
1284 virtual FormatToken getNextToken() {
1285 if (GreaterStashed) {
1286 FormatTok.NewlinesBefore = 0;
1287 FormatTok.WhiteSpaceStart =
1288 FormatTok.Tok.getLocation().getLocWithOffset(1);
1289 FormatTok.WhiteSpaceLength = 0;
1290 GreaterStashed = false;
1291 return FormatTok;
1292 }
1293
1294 FormatTok = FormatToken();
1295 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001296 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001297 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001298 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1299 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001300
1301 // Consume and record whitespace until we find a significant token.
1302 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +00001303 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001304 if (Newlines > 0)
1305 FormatTok.LastNewlineOffset =
1306 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001307 unsigned EscapedNewlines = Text.count("\\\n");
1308 FormatTok.NewlinesBefore += Newlines;
1309 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001310 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1311
1312 if (FormatTok.Tok.is(tok::eof))
1313 return FormatTok;
1314 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001315 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001316 }
Manuel Klimek95419382013-01-07 07:56:50 +00001317
1318 // Now FormatTok is the next non-whitespace token.
1319 FormatTok.TokenLength = Text.size();
1320
Manuel Klimekd4397b92013-01-04 23:34:14 +00001321 // In case the token starts with escaped newlines, we want to
1322 // take them into account as whitespace - this pattern is quite frequent
1323 // in macro definitions.
1324 // FIXME: What do we want to do with other escaped spaces, and escaped
1325 // spaces or newlines in the middle of tokens?
1326 // FIXME: Add a more explicit test.
1327 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001328 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001329 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001330 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001331 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001332 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001333 }
1334
1335 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001336 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001337 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001338 FormatTok.Tok.setKind(Info.getTokenID());
1339 }
1340
1341 if (FormatTok.Tok.is(tok::greatergreater)) {
1342 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001343 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001344 GreaterStashed = true;
1345 }
1346
Daniel Jasper812c0452013-03-01 16:45:59 +00001347 // If we reformat comments, we remove trailing whitespace. Update the length
1348 // accordingly.
1349 if (FormatTok.Tok.is(tok::comment))
1350 FormatTok.TokenLength = Text.rtrim().size();
1351
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001352 return FormatTok;
1353 }
1354
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001355 IdentifierTable &getIdentTable() { return IdentTable; }
1356
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001357private:
1358 FormatToken FormatTok;
1359 bool GreaterStashed;
1360 Lexer &Lex;
1361 SourceManager &SourceMgr;
1362 IdentifierTable IdentTable;
1363
1364 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001365 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001366 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1367 Tok.getLength());
1368 }
1369};
1370
Daniel Jasperbac016b2012-12-03 18:12:45 +00001371class Formatter : public UnwrappedLineConsumer {
1372public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001373 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1374 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001375 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001376 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +00001377 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001378
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001379 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001380
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001381 tooling::Replacements format() {
1382 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1383 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1384 StructuralError = Parser.parse();
1385 unsigned PreviousEndOfLineColumn = 0;
1386 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1387 Tokens.getIdentTable().get("in"));
1388 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1389 Annotator.annotate(AnnotatedLines[i]);
1390 }
1391 deriveLocalStyle();
1392 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1393 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1394 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001395
1396 // Adapt level to the next line if this is a comment.
1397 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001398 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001399 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1400 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1401 AnnotatedLines[i].First.Children.empty())
1402 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1403 else
1404 NextNoneCommentLine = AnnotatedLines[i].First.isNot(tok::r_brace)
1405 ? &AnnotatedLines[i]
1406 : NULL;
1407 }
1408
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001409 std::vector<int> IndentForLevel;
1410 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001411 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001412 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1413 E = AnnotatedLines.end();
1414 I != E; ++I) {
1415 const AnnotatedLine &TheLine = *I;
1416 const FormatToken &FirstTok = TheLine.First.FormatTok;
1417 int Offset = getIndentOffset(TheLine.First);
1418 while (IndentForLevel.size() <= TheLine.Level)
1419 IndentForLevel.push_back(-1);
1420 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf9955d32013-03-20 12:37:50 +00001421 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001422 if (TheLine.First.is(tok::eof)) {
1423 if (PreviousLineWasTouched) {
1424 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1425 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001426 /*WhitespaceStartColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001427 }
1428 } else if (TheLine.Type != LT_Invalid &&
1429 (WasMoved || touchesLine(TheLine))) {
1430 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1431 unsigned Indent = LevelIndent;
1432 if (static_cast<int>(Indent) + Offset >= 0)
1433 Indent += Offset;
1434 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperf9955d32013-03-20 12:37:50 +00001435 Indent = LevelIndent =
1436 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001437 } else {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001438 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1439 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001440 }
1441 tryFitMultipleLinesInOne(Indent, I, E);
1442 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1443 TheLine.First, Whitespaces,
1444 StructuralError);
1445 PreviousEndOfLineColumn =
1446 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1447 IndentForLevel[TheLine.Level] = LevelIndent;
1448 PreviousLineWasTouched = true;
1449 } else {
1450 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1451 unsigned Indent =
1452 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1453 unsigned LevelIndent = Indent;
1454 if (static_cast<int>(LevelIndent) - Offset >= 0)
1455 LevelIndent -= Offset;
Daniel Jasper83a90e52013-03-20 14:31:47 +00001456 if (TheLine.First.isNot(tok::comment))
1457 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001458
1459 // Remove trailing whitespace of the previous line if it was touched.
1460 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001461 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1462 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001463 }
1464 // If we did not reformat this unwrapped line, the column at the end of
1465 // the last token is unchanged - thus, we can calculate the end of the
1466 // last token.
1467 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1468 PreviousEndOfLineColumn =
1469 SourceMgr.getSpellingColumnNumber(LastLoc) +
1470 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1471 PreviousLineWasTouched = false;
Daniel Jasperc363dbb2013-03-22 16:25:51 +00001472 if (TheLine.Last->is(tok::comment))
1473 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1474 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001475 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001476 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001477 }
1478 return Whitespaces.generateReplacements();
1479 }
1480
1481private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001482 void deriveLocalStyle() {
1483 unsigned CountBoundToVariable = 0;
1484 unsigned CountBoundToType = 0;
1485 bool HasCpp03IncompatibleFormat = false;
1486 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1487 if (AnnotatedLines[i].First.Children.empty())
1488 continue;
1489 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1490 while (!Tok->Children.empty()) {
1491 if (Tok->Type == TT_PointerOrReference) {
1492 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1493 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1494 if (SpacesBefore && !SpacesAfter)
1495 ++CountBoundToVariable;
1496 else if (!SpacesBefore && SpacesAfter)
1497 ++CountBoundToType;
1498 }
1499
Daniel Jasper29f123b2013-02-08 15:28:42 +00001500 if (Tok->Type == TT_TemplateCloser &&
1501 Tok->Parent->Type == TT_TemplateCloser &&
1502 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001503 HasCpp03IncompatibleFormat = true;
1504 Tok = &Tok->Children[0];
1505 }
1506 }
1507 if (Style.DerivePointerBinding) {
1508 if (CountBoundToType > CountBoundToVariable)
1509 Style.PointerBindsToType = true;
1510 else if (CountBoundToType < CountBoundToVariable)
1511 Style.PointerBindsToType = false;
1512 }
1513 if (Style.Standard == FormatStyle::LS_Auto) {
1514 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1515 : FormatStyle::LS_Cpp03;
1516 }
1517 }
1518
Manuel Klimek547d5db2013-02-08 17:38:27 +00001519 /// \brief Get the indent of \p Level from \p IndentForLevel.
1520 ///
1521 /// \p IndentForLevel must contain the indent for the level \c l
1522 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1523 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001524 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001525 if (IndentForLevel[Level] != -1)
1526 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001527 if (Level == 0)
1528 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001529 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001530 }
1531
1532 /// \brief Get the offset of the line relatively to the level.
1533 ///
1534 /// For example, 'public:' labels in classes are offset by 1 or 2
1535 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001536 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001537 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001538 return Style.AccessModifierOffset;
1539 return 0;
1540 }
1541
Manuel Klimek517e8942013-01-11 17:54:10 +00001542 /// \brief Tries to merge lines into one.
1543 ///
1544 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1545 /// if possible; note that \c I will be incremented when lines are merged.
1546 ///
1547 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001548 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001549 std::vector<AnnotatedLine>::iterator &I,
1550 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001551 // We can never merge stuff if there are trailing line comments.
1552 if (I->Last->Type == TT_LineComment)
1553 return;
1554
Daniel Jaspera4d46212013-02-28 11:05:57 +00001555 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001556 // If we already exceed the column limit, we set 'Limit' to 0. The different
1557 // tryMerge..() functions can then decide whether to still do merging.
1558 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001559
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001560 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001561 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001562
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001563 if (I->Last->is(tok::l_brace)) {
1564 tryMergeSimpleBlock(I, E, Limit);
1565 } else if (I->First.is(tok::kw_if)) {
1566 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001567 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1568 I->First.FormatTok.IsFirst)) {
1569 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001570 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001571 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001572 }
1573
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001574 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1575 std::vector<AnnotatedLine>::iterator E,
1576 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001577 if (Limit == 0)
1578 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001579 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001580 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1581 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001582 if (I + 2 != E && (I + 2)->InPPDirective &&
1583 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1584 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001585 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001586 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001587 join(Line, *(++I));
1588 }
1589
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001590 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1591 std::vector<AnnotatedLine>::iterator E,
1592 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001593 if (Limit == 0)
1594 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001595 if (!Style.AllowShortIfStatementsOnASingleLine)
1596 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001597 if ((I + 1)->InPPDirective != I->InPPDirective ||
1598 ((I + 1)->InPPDirective &&
1599 (I + 1)->First.FormatTok.HasUnescapedNewline))
1600 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001601 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001602 if (Line.Last->isNot(tok::r_paren))
1603 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001604 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001605 return;
1606 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1607 return;
1608 // Only inline simple if's (no nested if or else).
1609 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1610 return;
1611 join(Line, *(++I));
1612 }
1613
1614 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001615 std::vector<AnnotatedLine>::iterator E,
1616 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001617 // First, check that the current line allows merging. This is the case if
1618 // we're not in a control flow statement and the last token is an opening
1619 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001620 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001621 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1622 tok::kw_else, tok::kw_try, tok::kw_catch,
1623 tok::kw_for,
1624 // This gets rid of all ObjC @ keywords and methods.
1625 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001626 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001627
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001628 AnnotatedToken *Tok = &(I + 1)->First;
1629 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001630 !Tok->MustBreakBefore) {
1631 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001632 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001633 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001634 join(Line, *(I + 1));
1635 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001636 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001637 // Check that we still have three lines and they fit into the limit.
1638 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1639 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001640 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001641
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001642 // Second, check that the next line does not contain any braces - if it
1643 // does, readability declines when putting it into a single line.
1644 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1645 return;
1646 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001647 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001648 return;
1649 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1650 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001651
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001652 // Last, check that the third line contains a single closing brace.
1653 Tok = &(I + 2)->First;
1654 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1655 Tok->MustBreakBefore)
1656 return;
1657
1658 join(Line, *(I + 1));
1659 join(Line, *(I + 2));
1660 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001661 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001662 }
1663
1664 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1665 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001666 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1667 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001668 }
1669
Daniel Jasper995e8202013-01-14 13:08:07 +00001670 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001671 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001672 A.Last->Children.push_back(B.First);
1673 while (!A.Last->Children.empty()) {
1674 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001675 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001676 A.Last = &A.Last->Children[0];
1677 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001678 }
1679
Daniel Jasper6f21a982013-03-13 07:49:51 +00001680 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001681 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1682 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1683 Ranges[i].getBegin()) &&
1684 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1685 Range.getBegin()))
1686 return true;
1687 }
1688 return false;
1689 }
1690
1691 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001692 const FormatToken *First = &TheLine.First.FormatTok;
1693 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001694 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001695 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1696 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001697 return touchesRanges(LineRange);
1698 }
1699
1700 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1701 const FormatToken *First = &TheLine.First.FormatTok;
1702 CharSourceRange LineRange = CharSourceRange::getCharRange(
1703 First->WhiteSpaceStart,
1704 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1705 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001706 }
1707
1708 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001709 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001710 }
1711
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001712 /// \brief Add a new line and the required indent before the first Token
1713 /// of the \c UnwrappedLine if there was no structural parsing error.
1714 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001715 void formatFirstToken(const AnnotatedToken &RootToken,
1716 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimek547d5db2013-02-08 17:38:27 +00001717 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001718 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001719
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001720 unsigned Newlines =
1721 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001722 if (Newlines == 0 && !Tok.IsFirst)
1723 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001724
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001725 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001726 // Insert extra new line before access specifiers.
1727 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1728 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1729 ++Newlines;
1730
Alexander Kornienko052685c2013-03-19 17:41:36 +00001731 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001732 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001733 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001734 PreviousEndOfLineColumn);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001735 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001736 }
1737
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001738 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001739 FormatStyle Style;
1740 Lexer &Lex;
1741 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001742 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001743 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001744 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001745 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001746};
1747
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001748tooling::Replacements
1749reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1750 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001751 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001752 OwningPtr<DiagnosticConsumer> DiagPrinter;
1753 if (DiagClient == 0) {
1754 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1755 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1756 DiagClient = DiagPrinter.get();
1757 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001758 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001759 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001760 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001761 Diagnostics.setSourceManager(&SourceMgr);
1762 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001763 return formatter.format();
1764}
1765
Daniel Jasper46ef8522013-01-10 13:08:12 +00001766LangOptions getFormattingLangOpts() {
1767 LangOptions LangOpts;
1768 LangOpts.CPlusPlus = 1;
1769 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001770 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001771 LangOpts.Bool = 1;
1772 LangOpts.ObjC1 = 1;
1773 LangOpts.ObjC2 = 1;
1774 return LangOpts;
1775}
1776
Daniel Jaspercd162382013-01-07 13:26:07 +00001777} // namespace format
1778} // namespace clang