blob: 84609d164e89fc35b28a114576f0146798c0ed0e [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000030#include <string>
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000051 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000065 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000067 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000068 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000069 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000070 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000071 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000078 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000079 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
80 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000081 return ChromiumStyle;
82}
83
Daniel Jasper94f0e132013-02-06 20:07:35 +000084static bool isTrailingComment(const AnnotatedToken &Tok) {
85 return Tok.is(tok::comment) &&
86 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
87}
88
Daniel Jasperacc33662013-02-08 08:22:00 +000089// Returns the length of everything up to the first possible line break after
90// the ), ], } or > matching \c Tok.
91static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
92 if (Tok.MatchingParen == NULL)
93 return 0;
94 AnnotatedToken *End = Tok.MatchingParen;
95 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
96 End = &End->Children[0];
97 }
98 return End->TotalLength - Tok.TotalLength + 1;
99}
100
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000101static size_t
102calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
103 // In preprocessor directives reserve two chars for trailing " \"
104 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
105}
106
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000107/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000108///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000109/// This includes special handling for certain constructs, e.g. the alignment of
110/// trailing line comments.
111class WhitespaceManager {
112public:
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000113 WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
114 : SourceMgr(SourceMgr), Style(Style) {}
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115
116 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
117 /// each \c AnnotatedToken.
118 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000119 unsigned Spaces, unsigned WhitespaceStartColumn) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000120 // 2+ newlines mean an empty line separating logic scopes.
121 if (NewLines >= 2)
122 alignComments();
123
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000124 SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
125 bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
126 Tok.FormatTok.TokenLength > Style.ColumnLimit;
127
Daniel Jasper304a9862013-01-21 22:49:20 +0000128 // Align line comments if they are trailing or if they continue other
129 // trailing comments.
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000130 if (isTrailingComment(Tok)) {
131 // Remove the comment's trailing whitespace.
132 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
133 Replaces.insert(tooling::Replacement(
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000134 SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000135 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
136
137 // Align comment with other comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000138 if ((Tok.Parent != NULL || !Comments.empty()) &&
139 !LineExceedsColumnLimit) {
140 StoredComment Comment;
141 Comment.Tok = Tok.FormatTok;
142 Comment.Spaces = Spaces;
143 Comment.NewLines = NewLines;
144 Comment.MinColumn =
145 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
146 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
147 Comment.Untouchable = false;
148 Comments.push_back(Comment);
149 return;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000150 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000151 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000152
153 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000154 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000155 alignComments();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000156
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000157 if (Tok.Type == TT_BlockComment) {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000158 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000159 } else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
160 StringRef Line(SourceMgr.getCharacterData(TokenLoc),
161 Tok.FormatTok.TokenLength);
162 int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
163 StringRef Prefix = getLineCommentPrefix(Line);
164 std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
165 splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
166 StartColumn + Prefix.size(), NewPrefix,
167 /*InPPDirective=*/ false,
168 /*CommentHasMoreLines=*/ false);
169 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000170
Manuel Klimek1998ea22013-02-20 10:15:13 +0000171 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000172 }
173
174 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
175 /// backslashes to escape newlines inside a preprocessor directive.
176 ///
177 /// This function and \c replaceWhitespace have the same behavior if
178 /// \c Newlines == 0.
179 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000180 unsigned Spaces, unsigned WhitespaceStartColumn) {
181 if (Tok.Type == TT_BlockComment)
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000182 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000183
184 storeReplacement(Tok.FormatTok,
185 getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000186 }
187
188 /// \brief Inserts a line break into the middle of a token.
189 ///
190 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
191 /// break and \p Postfix before the rest of the token starts in the next line.
192 ///
193 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
194 /// used to generate the correct line break.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000195 void breakToken(const FormatToken &Tok, unsigned Offset,
196 unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
197 bool InPPDirective, unsigned Spaces,
198 unsigned WhitespaceStartColumn) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000199 std::string NewLineText;
200 if (!InPPDirective)
201 NewLineText = getNewLineText(1, Spaces);
202 else
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000203 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000204 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000205 SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
206 Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
207 ReplacementText));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000208 }
209
210 /// \brief Returns all the \c Replacements created during formatting.
211 const tooling::Replacements &generateReplacements() {
212 alignComments();
213 return Replaces;
214 }
215
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000216 void addUntouchableComment(unsigned Column) {
217 StoredComment Comment;
218 Comment.MinColumn = Column;
219 Comment.MaxColumn = Column;
220 Comment.Untouchable = true;
221 Comments.push_back(Comment);
222 }
223
Manuel Klimek1998ea22013-02-20 10:15:13 +0000224private:
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000225 static StringRef getLineCommentPrefix(StringRef Comment) {
226 const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
227 for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
228 if (Comment.startswith(KnownPrefixes[i]))
229 return KnownPrefixes[i];
230 return "";
231 }
232
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000233 /// \brief Finds a common prefix of lines of a block comment to properly
234 /// indent (and possibly decorate with '*'s) added lines.
235 ///
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000236 /// The first line is ignored (it's special and starts with /*). The number of
237 /// lines should be more than one.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000238 static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
239 const char *PrefixChars = " *") {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000240 assert(Lines.size() > 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000241 StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
242 for (size_t i = 2; i < Lines.size(); ++i) {
243 for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
244 if (Prefix[j] != Lines[i][j]) {
245 Prefix = Prefix.substr(0, j);
246 break;
247 }
248 }
249 }
250 return Prefix;
251 }
252
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000253 /// \brief Splits one line in a line or block comment, if it doesn't fit to
254 /// provided column limit. Removes trailing whitespace in each line.
255 ///
256 /// \param Line points to the line contents without leading // or /*.
257 ///
258 /// \param StartColumn is the column where the first character of Line will be
259 /// located after formatting.
260 ///
261 /// \param LinePrefix is inserted after each line break.
262 ///
263 /// When \param InPPDirective is true, each line break will be preceded by a
264 /// backslash in the last column to make line breaks inside the comment
265 /// visually consistent with line breaks outside the comment. This only makes
266 /// sense for block comments.
267 ///
268 /// When \param CommentHasMoreLines is false, no line breaks/trailing
269 /// backslashes will be inserted after it.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000270 void splitLineInComment(const FormatToken &Tok, StringRef Line,
271 size_t StartColumn, StringRef LinePrefix,
272 bool InPPDirective, bool CommentHasMoreLines,
273 const char *WhiteSpaceChars = " ") {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000274 size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000275 const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000276
277 StringRef TrimmedLine = Line.rtrim();
278 int TrailingSpaceLength = Line.size() - TrimmedLine.size();
279
280 // Don't touch leading whitespace.
281 Line = TrimmedLine.ltrim();
282 StartColumn += TrimmedLine.size() - Line.size();
283
284 while (Line.size() + StartColumn > ColumnLimit) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000285 // Try to break at the last whitespace before the column limit.
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000286 size_t SpacePos =
287 Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000288 if (SpacePos == StringRef::npos) {
289 // Try to find any whitespace in the line.
290 SpacePos = Line.find_first_of(WhiteSpaceChars);
291 if (SpacePos == StringRef::npos) // No whitespace found, give up.
292 break;
293 }
294
295 StringRef NextCut = Line.substr(0, SpacePos).rtrim();
296 StringRef RemainingLine = Line.substr(SpacePos).ltrim();
297 if (RemainingLine.empty())
298 break;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000299
300 if (RemainingLine == "*/" && LinePrefix.endswith("* "))
301 LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
302
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000303 Line = RemainingLine;
304
305 size_t ReplaceChars = Line.begin() - NextCut.end();
306 breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000307 InPPDirective, 0, NextCut.size() + StartColumn);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000308 StartColumn = LinePrefix.size();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000309 }
310
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000311 if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
312 // Remove trailing whitespace/insert backslash. + 1 is for \n
313 breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
314 InPPDirective, 0, Line.size() + StartColumn);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000315 }
316 }
317
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000318 /// \brief Changes indentation of all lines in a block comment by Indent,
319 /// removes trailing whitespace from each line, splits lines that end up
320 /// exceeding the column limit.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000321 void indentBlockComment(const AnnotatedToken &Tok, int Indent,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000322 int WhitespaceStartColumn, int NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000323 bool InPPDirective) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000324 assert(Tok.Type == TT_BlockComment);
325 int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000326 const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
327 const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
328 const int IndentDelta = Indent - CurrentIndent;
329 const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
330 Tok.FormatTok.TokenLength);
331 assert(Text.startswith("/*") && Text.endswith("*/"));
332
333 SmallVector<StringRef, 16> Lines;
334 Text.split(Lines, "\n");
335
336 if (IndentDelta > 0) {
337 std::string WhiteSpace(IndentDelta, ' ');
338 for (size_t i = 1; i < Lines.size(); ++i) {
339 Replaces.insert(tooling::Replacement(
340 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
341 0, WhiteSpace));
342 }
343 } else if (IndentDelta < 0) {
344 std::string WhiteSpace(-IndentDelta, ' ');
345 // Check that the line is indented enough.
346 for (size_t i = 1; i < Lines.size(); ++i) {
347 if (!Lines[i].startswith(WhiteSpace))
348 return;
349 }
350 for (size_t i = 1; i < Lines.size(); ++i) {
351 Replaces.insert(tooling::Replacement(
352 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
353 -IndentDelta, ""));
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000354 }
355 }
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000356
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000357 // Split long lines in comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000358 size_t OldPrefixSize = 0;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000359 std::string NewPrefix;
360 if (Lines.size() > 1) {
361 StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000362 OldPrefixSize = CurrentPrefix.size();
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000363 NewPrefix = (IndentDelta < 0)
364 ? CurrentPrefix.substr(-IndentDelta).str()
365 : std::string(IndentDelta, ' ') + CurrentPrefix.str();
366 if (CurrentPrefix.endswith("*")) {
367 NewPrefix += " ";
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000368 ++OldPrefixSize;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000369 }
370 } else if (Tok.Parent == 0) {
371 NewPrefix = std::string(StartColumn, ' ') + " * ";
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000372 }
373
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000374 StartColumn += 2;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000375 for (size_t i = 0; i < Lines.size(); ++i) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000376 StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000377 splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
378 InPPDirective, i != Lines.size() - 1);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000379 StartColumn = NewPrefix.size();
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000380 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000381 }
382
Manuel Klimek1998ea22013-02-20 10:15:13 +0000383 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
384 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
385 }
386
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000387 std::string getNewLineText(unsigned NewLines, unsigned Spaces,
388 unsigned WhitespaceStartColumn) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000389 std::string NewLineText;
390 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000391 unsigned Offset =
392 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000393 for (unsigned i = 0; i < NewLines; ++i) {
394 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
395 NewLineText += "\\\n";
396 Offset = 0;
397 }
398 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000399 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000400 }
401
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000402 /// \brief Structure to store a comment for later layout and alignment.
403 struct StoredComment {
404 FormatToken Tok;
405 unsigned MinColumn;
406 unsigned MaxColumn;
407 unsigned NewLines;
408 unsigned Spaces;
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000409 bool Untouchable;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000410 };
411 SmallVector<StoredComment, 16> Comments;
412 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
413
414 /// \brief Try to align all stashed comments.
415 void alignComments() {
416 unsigned MinColumn = 0;
417 unsigned MaxColumn = UINT_MAX;
418 comment_iterator Start = Comments.begin();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000419 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000420 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
421 alignComments(Start, I, MinColumn);
422 MinColumn = I->MinColumn;
423 MaxColumn = I->MaxColumn;
424 Start = I;
425 } else {
426 MinColumn = std::max(MinColumn, I->MinColumn);
427 MaxColumn = std::min(MaxColumn, I->MaxColumn);
428 }
429 }
430 alignComments(Start, Comments.end(), MinColumn);
431 Comments.clear();
432 }
433
434 /// \brief Put all the comments between \p I and \p E into \p Column.
435 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
436 while (I != E) {
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000437 if (!I->Untouchable) {
438 unsigned Spaces = I->Spaces + Column - I->MinColumn;
Alexander Kornienkofd433362013-03-27 17:08:02 +0000439 storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000440 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000441 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000442 }
443 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000444
445 /// \brief Stores \p Text as the replacement for the whitespace in front of
446 /// \p Tok.
447 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000448 // Don't create a replacement, if it does not change anything.
449 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
450 Tok.WhiteSpaceLength) == Text)
451 return;
452
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000453 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
454 Tok.WhiteSpaceLength, Text));
455 }
456
457 SourceManager &SourceMgr;
458 tooling::Replacements Replaces;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000459 const FormatStyle &Style;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000460};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000461
Daniel Jasperf7935112012-12-03 18:12:45 +0000462class UnwrappedLineFormatter {
463public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000464 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000465 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000466 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000467 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000468 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000469 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000470 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000471
Manuel Klimek1abf7892013-01-04 23:34:14 +0000472 /// \brief Formats an \c UnwrappedLine.
473 ///
474 /// \returns The column after the last token in the last line of the
475 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000476 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000477 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000478 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000479 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000480 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000481 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000482 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper97b89482013-03-13 07:49:51 +0000483 /*HasMultiParameterLine=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000484 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000485 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000486 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000487 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000488
489 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000490 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000491
Daniel Jasper4b866272013-02-01 11:00:45 +0000492 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000493 unsigned ColumnLimit = Style.ColumnLimit;
494 if (NextLine && NextLine->InPPDirective &&
495 !NextLine->First.FormatTok.HasUnescapedNewline)
496 ColumnLimit = getColumnLimit();
497 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000498 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000499 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000500 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000501 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000503
Daniel Jasperacc33662013-02-08 08:22:00 +0000504 // If the ObjC method declaration does not fit on a line, we should format
505 // it with one arg per line.
506 if (Line.Type == LT_ObjCMethodDecl)
507 State.Stack.back().BreakBeforeParameter = true;
508
Daniel Jasper4b866272013-02-01 11:00:45 +0000509 // Find best solution in solution space.
510 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000511 }
512
513private:
Manuel Klimek24998102013-01-16 14:55:28 +0000514 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
515 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000516 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
517 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000518 llvm::errs();
519 }
520
Daniel Jasper337816e2013-01-11 10:22:12 +0000521 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000522 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
523 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000524 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
525 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000526 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000527 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasperc238c872013-04-02 14:33:13 +0000528 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
Daniel Jaspera628c982013-04-03 13:36:17 +0000529 CallContinuation(0), VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000530
Daniel Jasperf7935112012-12-03 18:12:45 +0000531 /// \brief The position to which a specific parenthesis level needs to be
532 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000533 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000534
Daniel Jaspere9de2602012-12-06 09:56:08 +0000535 /// \brief The position of the last space on each level.
536 ///
537 /// Used e.g. to break like:
538 /// functionCall(Parameter, otherCall(
539 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000541
Daniel Jaspere9de2602012-12-06 09:56:08 +0000542 /// \brief The position the first "<<" operator encountered on each level.
543 ///
544 /// Used to align "<<" operators. 0 if no such operator has been encountered
545 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000546 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000547
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000548 /// \brief Whether a newline needs to be inserted before the block's closing
549 /// brace.
550 ///
551 /// We only want to insert a newline before the closing brace if there also
552 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000553 bool BreakBeforeClosingBrace;
554
Daniel Jasperca6623b2013-01-28 12:45:14 +0000555 /// \brief The column of a \c ? in a conditional expression;
556 unsigned QuestionColumn;
557
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000558 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
559 /// lines, in this context.
560 bool AvoidBinPacking;
561
562 /// \brief Break after the next comma (or all the commas in this context if
563 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000564 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000565
566 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000567 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000568
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000569 /// \brief The position of the colon in an ObjC method declaration/call.
570 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000571
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000572 /// \brief The start of the most recent function in a builder-type call.
573 unsigned StartOfFunctionCall;
574
Daniel Jasperc238c872013-04-02 14:33:13 +0000575 /// \brief If a nested name specifier was broken over multiple lines, this
576 /// contains the start column of the second line. Otherwise 0.
577 unsigned NestedNameSpecifierContinuation;
578
579 /// \brief If a call expression was broken over multiple lines, this
580 /// contains the start column of the second line. Otherwise 0.
581 unsigned CallContinuation;
582
Daniel Jaspera628c982013-04-03 13:36:17 +0000583 /// \brief The column of the first variable name in a variable declaration.
584 ///
585 /// Used to align further variables if necessary.
586 unsigned VariablePos;
587
Daniel Jasper337816e2013-01-11 10:22:12 +0000588 bool operator<(const ParenState &Other) const {
589 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000590 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000591 if (LastSpace != Other.LastSpace)
592 return LastSpace < Other.LastSpace;
593 if (FirstLessLess != Other.FirstLessLess)
594 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000595 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
596 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000597 if (QuestionColumn != Other.QuestionColumn)
598 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000599 if (AvoidBinPacking != Other.AvoidBinPacking)
600 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000601 if (BreakBeforeParameter != Other.BreakBeforeParameter)
602 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000603 if (HasMultiParameterLine != Other.HasMultiParameterLine)
604 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000605 if (ColonPos != Other.ColonPos)
606 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000607 if (StartOfFunctionCall != Other.StartOfFunctionCall)
608 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000609 if (NestedNameSpecifierContinuation !=
610 Other.NestedNameSpecifierContinuation)
611 return NestedNameSpecifierContinuation <
612 Other.NestedNameSpecifierContinuation;
613 if (CallContinuation != Other.CallContinuation)
614 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000615 if (VariablePos != Other.VariablePos)
616 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000617 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000618 }
619 };
620
621 /// \brief The current state when indenting a unwrapped line.
622 ///
623 /// As the indenting tries different combinations this is copied by value.
624 struct LineState {
625 /// \brief The number of used columns in the current line.
626 unsigned Column;
627
628 /// \brief The token that needs to be next formatted.
629 const AnnotatedToken *NextToken;
630
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000631 /// \brief \c true if this line contains a continued for-loop section.
632 bool LineContainsContinuedForLoopSection;
633
Daniel Jasper400adc62013-02-08 15:28:42 +0000634 /// \brief The level of nesting inside (), [], <> and {}.
635 unsigned ParenLevel;
636
Daniel Jasper40c36c52013-02-18 11:05:07 +0000637 /// \brief The \c ParenLevel at the start of this line.
638 unsigned StartOfLineLevel;
639
Manuel Klimek02f640a2013-02-20 15:25:48 +0000640 /// \brief The start column of the string literal, if we're in a string
641 /// literal sequence, 0 otherwise.
642 unsigned StartOfStringLiteral;
643
Daniel Jasper337816e2013-01-11 10:22:12 +0000644 /// \brief A stack keeping track of properties applying to parenthesis
645 /// levels.
646 std::vector<ParenState> Stack;
647
648 /// \brief Comparison operator to be able to used \c LineState in \c map.
649 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000650 if (NextToken != Other.NextToken)
651 return NextToken < Other.NextToken;
652 if (Column != Other.Column)
653 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000654 if (LineContainsContinuedForLoopSection !=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000655 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000656 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000657 if (ParenLevel != Other.ParenLevel)
658 return ParenLevel < Other.ParenLevel;
659 if (StartOfLineLevel != Other.StartOfLineLevel)
660 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000661 if (StartOfStringLiteral != Other.StartOfStringLiteral)
662 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000663 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000664 }
665 };
666
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000667 /// \brief Appends the next token to \p State and updates information
668 /// necessary for indentation.
669 ///
670 /// Puts the token on the current line if \p Newline is \c true and adds a
671 /// line break and necessary indentation otherwise.
672 ///
673 /// If \p DryRun is \c false, also creates and stores the required
674 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000675 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000676 const AnnotatedToken &Current = *State.NextToken;
677 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000678
Daniel Jasper291f9362013-03-20 15:58:10 +0000679 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000680 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
681 State.NextToken->FormatTok.TokenLength;
682 if (State.NextToken->Children.empty())
683 State.NextToken = NULL;
684 else
685 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000686 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000687 }
688
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000689 // If we are continuing an expression, we want to indent an extra 4 spaces.
690 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000691 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000693 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000694 if (Current.is(tok::r_brace)) {
695 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000696 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000697 State.StartOfStringLiteral != 0) {
698 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000699 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000700 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000701 State.Stack.back().FirstLessLess != 0) {
702 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000703 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000704 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
705 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000706 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000707 } else {
708 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
709 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000710 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000711 if (State.Stack.back().CallContinuation == 0) {
712 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000713 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000714 } else {
715 State.Column = State.Stack.back().CallContinuation;
716 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000717 } else if (Current.Type == TT_ConditionalExpr) {
718 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000719 } else if (Previous.is(tok::comma) &&
720 State.Stack.back().VariablePos != 0) {
721 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000722 } else if (Previous.ClosesTemplateDeclaration ||
723 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000724 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000725 } else if (Current.Type == TT_ObjCSelectorName) {
726 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
727 State.Column =
728 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
729 } else {
730 State.Column = State.Stack.back().Indent;
731 State.Stack.back().ColonPos =
732 State.Column + Current.FormatTok.TokenLength;
733 }
Daniel Jasper6bee6822013-04-08 20:33:42 +0000734 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000735 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000736 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000737 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000738 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000739 // Ensure that we fall back to indenting 4 spaces instead of just
740 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000741 if (State.Column == FirstIndent)
742 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000743 }
744
Daniel Jasper54a86022013-02-15 11:07:25 +0000745 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000746 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000747 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000748 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000749 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000750
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000751 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000752 unsigned NewLines = 1;
753 if (Current.Type == TT_LineComment)
754 NewLines =
755 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
756 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000757 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000758 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000759 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000760 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000761 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000762 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000763 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000764
Daniel Jasper400adc62013-02-08 15:28:42 +0000765 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000766 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000767
768 // Any break on this level means that the parent level has been broken
769 // and we need to avoid bin packing there.
770 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
771 State.Stack[i].BreakBeforeParameter = true;
772 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000773 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000774 State.Stack.back().BreakBeforeParameter = true;
775
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000776 // If we break after {, we should also break before the corresponding }.
777 if (Previous.is(tok::l_brace))
778 State.Stack.back().BreakBeforeClosingBrace = true;
779
780 if (State.Stack.back().AvoidBinPacking) {
781 // If we are breaking after '(', '{', '<', this is not bin packing
782 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000783 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000784 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
785 Line.MustBeDeclaration))
786 State.Stack.back().BreakBeforeParameter = true;
787 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000788 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000789 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000790 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
791 State.Stack.back().VariablePos == 0) {
792 State.Stack.back().VariablePos = State.Column;
793 // Move over * and & if they are bound to the variable name.
794 const AnnotatedToken *Tok = &Previous;
795 while (Tok &&
796 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
797 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
798 if (Tok->SpacesRequiredBefore != 0)
799 break;
800 Tok = Tok->Parent;
801 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000802 if (Previous.PartOfMultiVariableDeclStmt)
803 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
804 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000805
Daniel Jaspereef30492013-02-11 12:36:37 +0000806 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000807
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000809 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000810
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000811 if (Current.Type == TT_ObjCSelectorName &&
812 State.Stack.back().ColonPos == 0) {
813 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000814 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000815 State.Stack.back().ColonPos =
816 State.Stack.back().Indent + Current.LongestObjCSelectorName;
817 else
818 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000819 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000820 }
821
Daniel Jasper6bee6822013-04-08 20:33:42 +0000822 if (opensScope(Previous) && Previous.Type != TT_ObjCMethodExpr &&
823 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000824 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000825 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000826 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000827
Daniel Jaspere9de2602012-12-06 09:56:08 +0000828 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000829 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000830 // Treat the condition inside an if as if it was a second function
831 // parameter, i.e. let nested calls have an indent of 4.
832 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000833 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000834 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000835 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000836 Previous.Type == TT_ConditionalExpr ||
837 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000838 getPrecedence(Previous) != prec::Assignment)
839 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000840 else if (Previous.Type == TT_InheritanceColon)
841 State.Stack.back().Indent = State.Column;
Daniel Jasper6bee6822013-04-08 20:33:42 +0000842 else if (opensScope(Previous) && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000843 // If this function has multiple parameters, indent nested calls from
844 // the start of the first parameter.
845 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000846 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000847
Manuel Klimek1998ea22013-02-20 10:15:13 +0000848 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000849 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000850
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000851 /// \brief Mark the next token as consumed in \p State and modify its stacks
852 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000853 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000854 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000855 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000856
Daniel Jaspereead02b2013-02-14 08:42:54 +0000857 if (Current.Type == TT_InheritanceColon)
858 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000859 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
860 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000861 if (Current.is(tok::question))
862 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000863 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000864 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
865 State.Stack.back().StartOfFunctionCall =
866 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000867 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000868 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000869 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
870 State.Stack.back().AvoidBinPacking = true;
871 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000872 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000873
Daniel Jasper6bee6822013-04-08 20:33:42 +0000874 // If return returns a binary expression, align after it.
875 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
876 State.Stack.back().LastSpace = State.Column + 7;
877
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000878 // In ObjC method declaration we align on the ":" of parameters, but we need
879 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000880 if (Current.Type == TT_ObjCMethodSpecifier)
881 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000882
Daniel Jasper400adc62013-02-08 15:28:42 +0000883 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000884 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
885 // Don't add extra indentation for the first fake parenthesis after
886 // 'return', assignements or opening <({[. The indentation for these cases
887 // is special cased.
888 bool SkipFirstExtraIndent =
889 Current.is(tok::kw_return) ||
890 (Previous && (opensScope(*Previous) ||
891 getPrecedence(*Previous) == prec::Assignment));
892 for (SmallVector<prec::Level, 4>::const_reverse_iterator
893 I = Current.FakeLParens.rbegin(),
894 E = Current.FakeLParens.rend();
895 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000896 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000897 NewParenState.Indent =
898 std::max(std::max(State.Column, NewParenState.Indent),
899 State.Stack.back().LastSpace);
900
901 // Always indent conditional expressions. Never indent expression where
902 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
903 // prec::Assignment) as those have different indentation rules. Indent
904 // other expression, unless the indentation needs to be skipped.
905 if (*I == prec::Conditional ||
906 (!SkipFirstExtraIndent && *I > prec::Assignment))
907 NewParenState.Indent += 4;
908 if (Previous && !opensScope(*Previous))
909 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000910 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000911 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000912 }
913
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000914 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000915 // prepare for the following tokens.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000916 if (opensScope(Current)) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000917 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000918 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000919 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000920 NewIndent = 2 + State.Stack.back().LastSpace;
921 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000922 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000923 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
924 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000925 AvoidBinPacking =
926 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000927 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000928 State.Stack.push_back(
929 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
930 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000931 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000932 }
933
Daniel Jasperacc33662013-02-08 08:22:00 +0000934 // If this '[' opens an ObjC call, determine whether all parameters fit into
935 // one line and put one per line if they don't.
936 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
937 Current.MatchingParen != NULL) {
938 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
939 State.Stack.back().BreakBeforeParameter = true;
940 }
941
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000942 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000943 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000944 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000945 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
946 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000947 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000948 --State.ParenLevel;
949 }
950
951 // Remove scopes created by fake parenthesis.
952 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000953 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000954 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000955 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000957
Manuel Klimek0c915712013-02-20 15:32:58 +0000958 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000959 State.StartOfStringLiteral = State.Column;
960 } else if (Current.isNot(tok::comment)) {
961 State.StartOfStringLiteral = 0;
962 }
963
Manuel Klimek1998ea22013-02-20 10:15:13 +0000964 State.Column += Current.FormatTok.TokenLength;
965
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000966 if (State.NextToken->Children.empty())
967 State.NextToken = NULL;
968 else
969 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000970
Manuel Klimek1998ea22013-02-20 10:15:13 +0000971 return breakProtrudingToken(Current, State, DryRun);
972 }
973
974 /// \brief If the current token sticks out over the end of the line, break
975 /// it if possible.
976 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
977 bool DryRun) {
978 if (Current.isNot(tok::string_literal))
979 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000980 // Only break up default narrow strings.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000981 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
982 if (!LiteralData || *LiteralData != '"')
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000983 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000984
985 unsigned Penalty = 0;
986 unsigned TailOffset = 0;
987 unsigned TailLength = Current.FormatTok.TokenLength;
988 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
989 unsigned OffsetFromStart = 0;
990 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000991 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000992 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000993 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000994 StringRef::size_type SplitPoint = getSplitPoint(
995 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000996 if (SplitPoint == StringRef::npos)
997 break;
998 assert(SplitPoint != 0);
999 // +2, because 'Text' starts after the opening quotes, and does not
1000 // include the closing quote we need to insert.
1001 unsigned WhitespaceStartColumn =
1002 StartColumn + OffsetFromStart + SplitPoint + 2;
1003 State.Stack.back().LastSpace = StartColumn;
1004 if (!DryRun) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001005 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
1006 0, "\"", "\"", Line.InPPDirective, StartColumn,
1007 WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001008 }
1009 TailOffset += SplitPoint + 1;
1010 TailLength -= SplitPoint + 1;
1011 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +00001012 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +00001013 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1014 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001015 }
1016 State.Column = StartColumn + TailLength;
1017 return Penalty;
1018 }
1019
1020 StringRef::size_type
1021 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +00001022 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +00001023 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001024 return SpaceOffset;
1025 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +00001026 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001027 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001028 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
1029 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001030 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001031 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001032 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +00001033 }
1034
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001035 StringRef::size_type
1036 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
1037 StringRef::size_type NextEscape = Text.find('\\');
1038 while (NextEscape != StringRef::npos && NextEscape < Offset) {
1039 StringRef::size_type SequenceLength =
1040 getEscapeSequenceLength(Text.substr(NextEscape));
1041 if (Offset < NextEscape + SequenceLength)
1042 return NextEscape;
1043 NextEscape = Text.find('\\', NextEscape + SequenceLength);
1044 }
1045 return Offset;
1046 }
1047
1048 unsigned getEscapeSequenceLength(StringRef Text) {
1049 assert(Text[0] == '\\');
1050 if (Text.size() < 2)
1051 return 1;
1052
1053 switch (Text[1]) {
1054 case 'u':
1055 return 6;
1056 case 'U':
1057 return 10;
1058 case 'x':
1059 return getHexLength(Text);
1060 default:
1061 if (Text[1] >= '0' && Text[1] <= '7')
1062 return getOctalLength(Text);
1063 return 2;
1064 }
1065 }
1066
1067 unsigned getHexLength(StringRef Text) {
1068 unsigned I = 2; // Point after '\x'.
1069 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
1070 (Text[I] >= 'a' && Text[I] <= 'f') ||
1071 (Text[I] >= 'A' && Text[I] <= 'F'))) {
1072 ++I;
1073 }
1074 return I;
1075 }
1076
1077 unsigned getOctalLength(StringRef Text) {
1078 unsigned I = 1;
1079 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
1080 ++I;
1081 }
1082 return I;
1083 }
1084
Daniel Jasper2df93312013-01-09 10:16:05 +00001085 unsigned getColumnLimit() {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +00001086 return calculateColumnLimit(Style, Line.InPPDirective);
Daniel Jasper2df93312013-01-09 10:16:05 +00001087 }
1088
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001089 /// \brief An edge in the solution space from \c Previous->State to \c State,
1090 /// inserting a newline dependent on the \c NewLine.
1091 struct StateNode {
1092 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001093 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001094 LineState State;
1095 bool NewLine;
1096 StateNode *Previous;
1097 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001098
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001099 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1100 ///
1101 /// In case of equal penalties, we want to prefer states that were inserted
1102 /// first. During state generation we make sure that we insert states first
1103 /// that break the line as late as possible.
1104 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1105
1106 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1107 /// \c State has the given \c OrderedPenalty.
1108 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1109
1110 /// \brief The BFS queue type.
1111 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1112 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001113
1114 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001115 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001116 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1117 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1118 /// find the shortest path (the one with lowest penalty) from \p InitialState
1119 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001120 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001121 std::set<LineState> Seen;
1122
Daniel Jasper4b866272013-02-01 11:00:45 +00001123 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001124 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001125 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1126 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1127 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001128
1129 // While not empty, take first element and follow edges.
1130 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001131 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001132 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001133 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001134 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001135 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001136 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001137 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001138
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001139 if (!Seen.insert(Node->State).second)
1140 // State already examined with lower penalty.
1141 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001142
Manuel Klimekaf491072013-02-13 10:54:19 +00001143 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1144 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001145 }
1146
1147 if (Queue.empty())
1148 // We were unable to find a solution, do nothing.
1149 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +00001150 return 0;
1151
Daniel Jasper4b866272013-02-01 11:00:45 +00001152 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001153 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001154 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +00001155
Daniel Jasper4b866272013-02-01 11:00:45 +00001156 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001157 return Queue.top().second->State.Column;
1158 }
1159
1160 void reconstructPath(LineState &State, StateNode *Current) {
1161 // FIXME: This recursive implementation limits the possible number
1162 // of tokens per line if compiled into a binary with small stack space.
1163 // To become more independent of stack frame limitations we would need
1164 // to also change the TokenAnnotator.
1165 if (Current->Previous == NULL)
1166 return;
1167 reconstructPath(State, Current->Previous);
1168 DEBUG({
1169 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +00001170 llvm::errs()
1171 << "Penalty for splitting before "
1172 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1173 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001174 }
1175 });
1176 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +00001177 }
1178
Manuel Klimekaf491072013-02-13 10:54:19 +00001179 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001180 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001181 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001182 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001183 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1184 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001185 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001186 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001187 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001188 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001189 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001190 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1191
1192 StateNode *Node = new (Allocator.Allocate())
1193 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001194 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001195 if (Node->State.Column > getColumnLimit()) {
1196 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001197 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001198 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001199
1200 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1201 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001202 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001203
Daniel Jasper4b866272013-02-01 11:00:45 +00001204 /// \brief Returns \c true, if a line break after \p State is allowed.
1205 bool canBreak(const LineState &State) {
1206 if (!State.NextToken->CanBreakBefore &&
1207 !(State.NextToken->is(tok::r_brace) &&
1208 State.Stack.back().BreakBeforeClosingBrace))
1209 return false;
1210 // Trying to insert a parameter on a new line if there are already more than
1211 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +00001212 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001213 State.Stack.back().AvoidBinPacking)
1214 return false;
1215 return true;
1216 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001217
Daniel Jasper4b866272013-02-01 11:00:45 +00001218 /// \brief Returns \c true, if a line break after \p State is mandatory.
1219 bool mustBreak(const LineState &State) {
1220 if (State.NextToken->MustBreakBefore)
1221 return true;
1222 if (State.NextToken->is(tok::r_brace) &&
1223 State.Stack.back().BreakBeforeClosingBrace)
1224 return true;
1225 if (State.NextToken->Parent->is(tok::semi) &&
1226 State.LineContainsContinuedForLoopSection)
1227 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001228 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +00001229 State.NextToken->is(tok::question) ||
1230 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001231 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +00001232 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +00001233 State.NextToken->isNot(tok::r_paren) &&
1234 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001235 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +00001236 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1237 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001238 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001239 State.NextToken->LongestObjCSelectorName == 0 &&
1240 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001241 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001242 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1243 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001244 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001245 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001246 if (State.NextToken->Type == TT_InlineASMColon)
1247 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +00001248 // This prevents breaks like:
1249 // ...
1250 // SomeParameter, OtherParameter).DoSomething(
1251 // ...
1252 // As they hide "DoSomething" and generally bad for readability.
1253 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1254 getRemainingLength(State) + State.Column > getColumnLimit() &&
1255 State.ParenLevel < State.StartOfLineLevel)
1256 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001257 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001258 }
1259
Daniel Jasper9b334242013-03-15 14:57:30 +00001260 // Returns the total number of columns required for the remaining tokens.
1261 unsigned getRemainingLength(const LineState &State) {
1262 if (State.NextToken && State.NextToken->Parent)
1263 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1264 return 0;
1265 }
1266
Daniel Jasperf7935112012-12-03 18:12:45 +00001267 FormatStyle Style;
1268 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001269 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001270 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001271 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001272 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001273
1274 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1275 QueueType Queue;
1276 // Increasing count of \c StateNode items we have created. This is used
1277 // to create a deterministic order independent of the container.
1278 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001279};
1280
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281class LexerBasedFormatTokenSource : public FormatTokenSource {
1282public:
1283 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001284 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001285 IdentTable(Lex.getLangOpts()) {
1286 Lex.SetKeepWhitespaceMode(true);
1287 }
1288
1289 virtual FormatToken getNextToken() {
1290 if (GreaterStashed) {
1291 FormatTok.NewlinesBefore = 0;
1292 FormatTok.WhiteSpaceStart =
1293 FormatTok.Tok.getLocation().getLocWithOffset(1);
1294 FormatTok.WhiteSpaceLength = 0;
1295 GreaterStashed = false;
1296 return FormatTok;
1297 }
1298
1299 FormatTok = FormatToken();
1300 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001301 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001302 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001303 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1304 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001305
1306 // Consume and record whitespace until we find a significant token.
1307 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001308 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001309 if (Newlines > 0)
1310 FormatTok.LastNewlineOffset =
1311 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001312 unsigned EscapedNewlines = Text.count("\\\n");
1313 FormatTok.NewlinesBefore += Newlines;
1314 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001315 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1316
1317 if (FormatTok.Tok.is(tok::eof))
1318 return FormatTok;
1319 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001320 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001321 }
Manuel Klimekef920692013-01-07 07:56:50 +00001322
1323 // Now FormatTok is the next non-whitespace token.
1324 FormatTok.TokenLength = Text.size();
1325
Manuel Klimek1abf7892013-01-04 23:34:14 +00001326 // In case the token starts with escaped newlines, we want to
1327 // take them into account as whitespace - this pattern is quite frequent
1328 // in macro definitions.
1329 // FIXME: What do we want to do with other escaped spaces, and escaped
1330 // spaces or newlines in the middle of tokens?
1331 // FIXME: Add a more explicit test.
1332 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001333 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001334 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001335 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001336 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001337 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001338 }
1339
1340 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001341 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001342 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001343 FormatTok.Tok.setKind(Info.getTokenID());
1344 }
1345
1346 if (FormatTok.Tok.is(tok::greatergreater)) {
1347 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001348 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349 GreaterStashed = true;
1350 }
1351
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001352 // If we reformat comments, we remove trailing whitespace. Update the length
1353 // accordingly.
1354 if (FormatTok.Tok.is(tok::comment))
1355 FormatTok.TokenLength = Text.rtrim().size();
1356
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001357 return FormatTok;
1358 }
1359
Nico Weber29f9dea2013-02-11 15:32:15 +00001360 IdentifierTable &getIdentTable() { return IdentTable; }
1361
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001362private:
1363 FormatToken FormatTok;
1364 bool GreaterStashed;
1365 Lexer &Lex;
1366 SourceManager &SourceMgr;
1367 IdentifierTable IdentTable;
1368
1369 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001370 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001371 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1372 Tok.getLength());
1373 }
1374};
1375
Daniel Jasperf7935112012-12-03 18:12:45 +00001376class Formatter : public UnwrappedLineConsumer {
1377public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001378 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1379 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001380 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001381 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001382 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001383
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001384 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001385
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001386 tooling::Replacements format() {
1387 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1388 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1389 StructuralError = Parser.parse();
1390 unsigned PreviousEndOfLineColumn = 0;
1391 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1392 Tokens.getIdentTable().get("in"));
1393 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1394 Annotator.annotate(AnnotatedLines[i]);
1395 }
1396 deriveLocalStyle();
1397 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1398 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1399 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001400
1401 // Adapt level to the next line if this is a comment.
1402 // FIXME: Can/should this be done in the UnwrappedLineParser?
1403 const AnnotatedLine* NextNoneCommentLine = NULL;
1404 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1405 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1406 AnnotatedLines[i].First.Children.empty())
1407 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1408 else
1409 NextNoneCommentLine = AnnotatedLines[i].First.isNot(tok::r_brace)
1410 ? &AnnotatedLines[i]
1411 : NULL;
1412 }
1413
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001414 std::vector<int> IndentForLevel;
1415 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001416 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001417 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1418 E = AnnotatedLines.end();
1419 I != E; ++I) {
1420 const AnnotatedLine &TheLine = *I;
1421 const FormatToken &FirstTok = TheLine.First.FormatTok;
1422 int Offset = getIndentOffset(TheLine.First);
1423 while (IndentForLevel.size() <= TheLine.Level)
1424 IndentForLevel.push_back(-1);
1425 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001426 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001427 if (TheLine.First.is(tok::eof)) {
1428 if (PreviousLineWasTouched) {
1429 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1430 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001431 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001432 }
1433 } else if (TheLine.Type != LT_Invalid &&
1434 (WasMoved || touchesLine(TheLine))) {
1435 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1436 unsigned Indent = LevelIndent;
1437 if (static_cast<int>(Indent) + Offset >= 0)
1438 Indent += Offset;
1439 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001440 Indent = LevelIndent =
1441 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001442 } else {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001443 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1444 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001445 }
1446 tryFitMultipleLinesInOne(Indent, I, E);
1447 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1448 TheLine.First, Whitespaces,
1449 StructuralError);
1450 PreviousEndOfLineColumn =
1451 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1452 IndentForLevel[TheLine.Level] = LevelIndent;
1453 PreviousLineWasTouched = true;
1454 } else {
1455 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1456 unsigned Indent =
1457 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1458 unsigned LevelIndent = Indent;
1459 if (static_cast<int>(LevelIndent) - Offset >= 0)
1460 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001461 if (TheLine.First.isNot(tok::comment))
1462 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001463
1464 // Remove trailing whitespace of the previous line if it was touched.
1465 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001466 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1467 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001468 }
1469 // If we did not reformat this unwrapped line, the column at the end of
1470 // the last token is unchanged - thus, we can calculate the end of the
1471 // last token.
1472 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1473 PreviousEndOfLineColumn =
1474 SourceMgr.getSpellingColumnNumber(LastLoc) +
1475 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1476 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001477 if (TheLine.Last->is(tok::comment))
1478 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1479 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001480 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001481 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001482 }
1483 return Whitespaces.generateReplacements();
1484 }
1485
1486private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001487 void deriveLocalStyle() {
1488 unsigned CountBoundToVariable = 0;
1489 unsigned CountBoundToType = 0;
1490 bool HasCpp03IncompatibleFormat = false;
1491 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1492 if (AnnotatedLines[i].First.Children.empty())
1493 continue;
1494 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1495 while (!Tok->Children.empty()) {
1496 if (Tok->Type == TT_PointerOrReference) {
1497 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1498 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1499 if (SpacesBefore && !SpacesAfter)
1500 ++CountBoundToVariable;
1501 else if (!SpacesBefore && SpacesAfter)
1502 ++CountBoundToType;
1503 }
1504
Daniel Jasper400adc62013-02-08 15:28:42 +00001505 if (Tok->Type == TT_TemplateCloser &&
1506 Tok->Parent->Type == TT_TemplateCloser &&
1507 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001508 HasCpp03IncompatibleFormat = true;
1509 Tok = &Tok->Children[0];
1510 }
1511 }
1512 if (Style.DerivePointerBinding) {
1513 if (CountBoundToType > CountBoundToVariable)
1514 Style.PointerBindsToType = true;
1515 else if (CountBoundToType < CountBoundToVariable)
1516 Style.PointerBindsToType = false;
1517 }
1518 if (Style.Standard == FormatStyle::LS_Auto) {
1519 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1520 : FormatStyle::LS_Cpp03;
1521 }
1522 }
1523
Manuel Klimekb95f5452013-02-08 17:38:27 +00001524 /// \brief Get the indent of \p Level from \p IndentForLevel.
1525 ///
1526 /// \p IndentForLevel must contain the indent for the level \c l
1527 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1528 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001529 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001530 if (IndentForLevel[Level] != -1)
1531 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001532 if (Level == 0)
1533 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001534 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001535 }
1536
1537 /// \brief Get the offset of the line relatively to the level.
1538 ///
1539 /// For example, 'public:' labels in classes are offset by 1 or 2
1540 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001541 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001542 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001543 return Style.AccessModifierOffset;
1544 return 0;
1545 }
1546
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001547 /// \brief Tries to merge lines into one.
1548 ///
1549 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1550 /// if possible; note that \c I will be incremented when lines are merged.
1551 ///
1552 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001553 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001554 std::vector<AnnotatedLine>::iterator &I,
1555 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001556 // We can never merge stuff if there are trailing line comments.
1557 if (I->Last->Type == TT_LineComment)
1558 return;
1559
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001560 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001561 // If we already exceed the column limit, we set 'Limit' to 0. The different
1562 // tryMerge..() functions can then decide whether to still do merging.
1563 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001564
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001565 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001566 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001567
Daniel Jasper25837aa2013-01-14 14:14:23 +00001568 if (I->Last->is(tok::l_brace)) {
1569 tryMergeSimpleBlock(I, E, Limit);
1570 } else if (I->First.is(tok::kw_if)) {
1571 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001572 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1573 I->First.FormatTok.IsFirst)) {
1574 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001575 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001576 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001577 }
1578
Daniel Jasper39825ea2013-01-14 15:40:57 +00001579 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1580 std::vector<AnnotatedLine>::iterator E,
1581 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001582 if (Limit == 0)
1583 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001584 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001585 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1586 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001587 if (I + 2 != E && (I + 2)->InPPDirective &&
1588 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1589 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001590 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001591 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001592 join(Line, *(++I));
1593 }
1594
Daniel Jasper25837aa2013-01-14 14:14:23 +00001595 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1596 std::vector<AnnotatedLine>::iterator E,
1597 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001598 if (Limit == 0)
1599 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001600 if (!Style.AllowShortIfStatementsOnASingleLine)
1601 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001602 if ((I + 1)->InPPDirective != I->InPPDirective ||
1603 ((I + 1)->InPPDirective &&
1604 (I + 1)->First.FormatTok.HasUnescapedNewline))
1605 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001606 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001607 if (Line.Last->isNot(tok::r_paren))
1608 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001609 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001610 return;
1611 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1612 return;
1613 // Only inline simple if's (no nested if or else).
1614 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1615 return;
1616 join(Line, *(++I));
1617 }
1618
1619 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001620 std::vector<AnnotatedLine>::iterator E,
1621 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001622 // First, check that the current line allows merging. This is the case if
1623 // we're not in a control flow statement and the last token is an opening
1624 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001625 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001626 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1627 tok::kw_else, tok::kw_try, tok::kw_catch,
1628 tok::kw_for,
1629 // This gets rid of all ObjC @ keywords and methods.
1630 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001631 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001632
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001633 AnnotatedToken *Tok = &(I + 1)->First;
1634 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001635 !Tok->MustBreakBefore) {
1636 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001637 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001638 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001639 join(Line, *(I + 1));
1640 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001641 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001642 // Check that we still have three lines and they fit into the limit.
1643 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1644 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001645 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001646
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001647 // Second, check that the next line does not contain any braces - if it
1648 // does, readability declines when putting it into a single line.
1649 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1650 return;
1651 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001652 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001653 return;
1654 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1655 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001656
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001657 // Last, check that the third line contains a single closing brace.
1658 Tok = &(I + 2)->First;
1659 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1660 Tok->MustBreakBefore)
1661 return;
1662
1663 join(Line, *(I + 1));
1664 join(Line, *(I + 2));
1665 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001666 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001667 }
1668
1669 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1670 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001671 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1672 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001673 }
1674
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001675 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001676 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001677 A.Last->Children.push_back(B.First);
1678 while (!A.Last->Children.empty()) {
1679 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001680 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001681 A.Last = &A.Last->Children[0];
1682 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001683 }
1684
Daniel Jasper97b89482013-03-13 07:49:51 +00001685 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001686 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1687 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1688 Ranges[i].getBegin()) &&
1689 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1690 Range.getBegin()))
1691 return true;
1692 }
1693 return false;
1694 }
1695
1696 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001697 const FormatToken *First = &TheLine.First.FormatTok;
1698 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001699 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001700 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1701 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001702 return touchesRanges(LineRange);
1703 }
1704
1705 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1706 const FormatToken *First = &TheLine.First.FormatTok;
1707 CharSourceRange LineRange = CharSourceRange::getCharRange(
1708 First->WhiteSpaceStart,
1709 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1710 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001711 }
1712
1713 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001714 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001715 }
1716
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001717 /// \brief Add a new line and the required indent before the first Token
1718 /// of the \c UnwrappedLine if there was no structural parsing error.
1719 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001720 void formatFirstToken(const AnnotatedToken &RootToken,
1721 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001722 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001723 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001724
Daniel Jasperbbc84152013-01-29 11:27:30 +00001725 unsigned Newlines =
1726 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001727 if (Newlines == 0 && !Tok.IsFirst)
1728 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001729
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001730 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001731 // Insert extra new line before access specifiers.
1732 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1733 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1734 ++Newlines;
1735
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001736 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001737 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001738 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001739 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001740 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001741 }
1742
Alexander Kornienko116ba682013-01-14 11:34:14 +00001743 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001744 FormatStyle Style;
1745 Lexer &Lex;
1746 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001747 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001748 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001749 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001750 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001751};
1752
Daniel Jasperbbc84152013-01-29 11:27:30 +00001753tooling::Replacements
1754reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1755 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001756 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001757 OwningPtr<DiagnosticConsumer> DiagPrinter;
1758 if (DiagClient == 0) {
1759 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1760 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1761 DiagClient = DiagPrinter.get();
1762 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001763 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001764 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001765 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001766 Diagnostics.setSourceManager(&SourceMgr);
1767 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001768 return formatter.format();
1769}
1770
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001771LangOptions getFormattingLangOpts() {
1772 LangOptions LangOpts;
1773 LangOpts.CPlusPlus = 1;
1774 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001775 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001776 LangOpts.Bool = 1;
1777 LangOpts.ObjC1 = 1;
1778 LangOpts.ObjC2 = 1;
1779 return LangOpts;
1780}
1781
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001782} // namespace format
1783} // namespace clang