blob: 101b16f1a18c4aa176dbe17b1473c36e577b2427 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000026#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000027#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000030#include <string>
31
Daniel Jasperf7935112012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperf7935112012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000051 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000065 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000067 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000068 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000069 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000070 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000071 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper1b750ed2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000078 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000079 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
80 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000081 return ChromiumStyle;
82}
83
Daniel Jasper94f0e132013-02-06 20:07:35 +000084static bool isTrailingComment(const AnnotatedToken &Tok) {
85 return Tok.is(tok::comment) &&
86 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
87}
88
Daniel Jasperd1ae3582013-03-20 12:37:50 +000089static bool isComparison(const AnnotatedToken &Tok) {
90 prec::Level Precedence = getPrecedence(Tok);
91 return Tok.Type == TT_BinaryOperator &&
92 (Precedence == prec::Equality || Precedence == prec::Relational);
93}
94
Daniel Jasperacc33662013-02-08 08:22:00 +000095// Returns the length of everything up to the first possible line break after
96// the ), ], } or > matching \c Tok.
97static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
98 if (Tok.MatchingParen == NULL)
99 return 0;
100 AnnotatedToken *End = Tok.MatchingParen;
101 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
102 End = &End->Children[0];
103 }
104 return End->TotalLength - Tok.TotalLength + 1;
105}
106
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000107static size_t
108calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
109 // In preprocessor directives reserve two chars for trailing " \"
110 return Style.ColumnLimit - (InPPDirective ? 2 : 0);
111}
112
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000113/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000114///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000115/// This includes special handling for certain constructs, e.g. the alignment of
116/// trailing line comments.
117class WhitespaceManager {
118public:
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000119 WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
120 : SourceMgr(SourceMgr), Style(Style) {}
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000121
122 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
123 /// each \c AnnotatedToken.
124 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000125 unsigned Spaces, unsigned WhitespaceStartColumn) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000126 // 2+ newlines mean an empty line separating logic scopes.
127 if (NewLines >= 2)
128 alignComments();
129
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000130 SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
131 bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
132 Tok.FormatTok.TokenLength > Style.ColumnLimit;
133
Daniel Jasper304a9862013-01-21 22:49:20 +0000134 // Align line comments if they are trailing or if they continue other
135 // trailing comments.
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000136 if (isTrailingComment(Tok)) {
137 // Remove the comment's trailing whitespace.
138 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
139 Replaces.insert(tooling::Replacement(
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000140 SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000141 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
142
143 // Align comment with other comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000144 if ((Tok.Parent != NULL || !Comments.empty()) &&
145 !LineExceedsColumnLimit) {
146 StoredComment Comment;
147 Comment.Tok = Tok.FormatTok;
148 Comment.Spaces = Spaces;
149 Comment.NewLines = NewLines;
150 Comment.MinColumn =
151 NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
152 Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
153 Comment.Untouchable = false;
154 Comments.push_back(Comment);
155 return;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000156 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000157 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000158
159 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000160 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000161 alignComments();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000162
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000163 if (Tok.Type == TT_BlockComment) {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000164 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000165 } else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
166 StringRef Line(SourceMgr.getCharacterData(TokenLoc),
167 Tok.FormatTok.TokenLength);
168 int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
169 StringRef Prefix = getLineCommentPrefix(Line);
170 std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
171 splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
172 StartColumn + Prefix.size(), NewPrefix,
173 /*InPPDirective=*/ false,
174 /*CommentHasMoreLines=*/ false);
175 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000176
Manuel Klimek1998ea22013-02-20 10:15:13 +0000177 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000178 }
179
180 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
181 /// backslashes to escape newlines inside a preprocessor directive.
182 ///
183 /// This function and \c replaceWhitespace have the same behavior if
184 /// \c Newlines == 0.
185 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000186 unsigned Spaces, unsigned WhitespaceStartColumn) {
187 if (Tok.Type == TT_BlockComment)
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000188 indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000189
190 storeReplacement(Tok.FormatTok,
191 getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000192 }
193
194 /// \brief Inserts a line break into the middle of a token.
195 ///
196 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
197 /// break and \p Postfix before the rest of the token starts in the next line.
198 ///
199 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
200 /// used to generate the correct line break.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000201 void breakToken(const FormatToken &Tok, unsigned Offset,
202 unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
203 bool InPPDirective, unsigned Spaces,
204 unsigned WhitespaceStartColumn) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000205 std::string NewLineText;
206 if (!InPPDirective)
207 NewLineText = getNewLineText(1, Spaces);
208 else
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000209 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000210 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000211 SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
212 Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
213 ReplacementText));
Manuel Klimek1998ea22013-02-20 10:15:13 +0000214 }
215
216 /// \brief Returns all the \c Replacements created during formatting.
217 const tooling::Replacements &generateReplacements() {
218 alignComments();
219 return Replaces;
220 }
221
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000222 void addUntouchableComment(unsigned Column) {
223 StoredComment Comment;
224 Comment.MinColumn = Column;
225 Comment.MaxColumn = Column;
226 Comment.Untouchable = true;
227 Comments.push_back(Comment);
228 }
229
Manuel Klimek1998ea22013-02-20 10:15:13 +0000230private:
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000231 static StringRef getLineCommentPrefix(StringRef Comment) {
232 const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
233 for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
234 if (Comment.startswith(KnownPrefixes[i]))
235 return KnownPrefixes[i];
236 return "";
237 }
238
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000239 /// \brief Finds a common prefix of lines of a block comment to properly
240 /// indent (and possibly decorate with '*'s) added lines.
241 ///
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000242 /// The first line is ignored (it's special and starts with /*). The number of
243 /// lines should be more than one.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000244 static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
245 const char *PrefixChars = " *") {
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000246 assert(Lines.size() > 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000247 StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
248 for (size_t i = 2; i < Lines.size(); ++i) {
249 for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
250 if (Prefix[j] != Lines[i][j]) {
251 Prefix = Prefix.substr(0, j);
252 break;
253 }
254 }
255 }
256 return Prefix;
257 }
258
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000259 /// \brief Splits one line in a line or block comment, if it doesn't fit to
260 /// provided column limit. Removes trailing whitespace in each line.
261 ///
262 /// \param Line points to the line contents without leading // or /*.
263 ///
264 /// \param StartColumn is the column where the first character of Line will be
265 /// located after formatting.
266 ///
267 /// \param LinePrefix is inserted after each line break.
268 ///
269 /// When \param InPPDirective is true, each line break will be preceded by a
270 /// backslash in the last column to make line breaks inside the comment
271 /// visually consistent with line breaks outside the comment. This only makes
272 /// sense for block comments.
273 ///
274 /// When \param CommentHasMoreLines is false, no line breaks/trailing
275 /// backslashes will be inserted after it.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000276 void splitLineInComment(const FormatToken &Tok, StringRef Line,
277 size_t StartColumn, StringRef LinePrefix,
278 bool InPPDirective, bool CommentHasMoreLines,
279 const char *WhiteSpaceChars = " ") {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000280 size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000281 const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000282
283 StringRef TrimmedLine = Line.rtrim();
284 int TrailingSpaceLength = Line.size() - TrimmedLine.size();
285
286 // Don't touch leading whitespace.
287 Line = TrimmedLine.ltrim();
288 StartColumn += TrimmedLine.size() - Line.size();
289
290 while (Line.size() + StartColumn > ColumnLimit) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000291 // Try to break at the last whitespace before the column limit.
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000292 size_t SpacePos =
293 Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000294 if (SpacePos == StringRef::npos) {
295 // Try to find any whitespace in the line.
296 SpacePos = Line.find_first_of(WhiteSpaceChars);
297 if (SpacePos == StringRef::npos) // No whitespace found, give up.
298 break;
299 }
300
301 StringRef NextCut = Line.substr(0, SpacePos).rtrim();
302 StringRef RemainingLine = Line.substr(SpacePos).ltrim();
303 if (RemainingLine.empty())
304 break;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000305
306 if (RemainingLine == "*/" && LinePrefix.endswith("* "))
307 LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
308
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000309 Line = RemainingLine;
310
311 size_t ReplaceChars = Line.begin() - NextCut.end();
312 breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000313 InPPDirective, 0, NextCut.size() + StartColumn);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000314 StartColumn = LinePrefix.size();
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000315 }
316
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000317 if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
318 // Remove trailing whitespace/insert backslash. + 1 is for \n
319 breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
320 InPPDirective, 0, Line.size() + StartColumn);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000321 }
322 }
323
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000324 /// \brief Changes indentation of all lines in a block comment by Indent,
325 /// removes trailing whitespace from each line, splits lines that end up
326 /// exceeding the column limit.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000327 void indentBlockComment(const AnnotatedToken &Tok, int Indent,
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000328 int WhitespaceStartColumn, int NewLines,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000329 bool InPPDirective) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000330 assert(Tok.Type == TT_BlockComment);
331 int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000332 const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
333 const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
334 const int IndentDelta = Indent - CurrentIndent;
335 const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
336 Tok.FormatTok.TokenLength);
337 assert(Text.startswith("/*") && Text.endswith("*/"));
338
339 SmallVector<StringRef, 16> Lines;
340 Text.split(Lines, "\n");
341
342 if (IndentDelta > 0) {
343 std::string WhiteSpace(IndentDelta, ' ');
344 for (size_t i = 1; i < Lines.size(); ++i) {
345 Replaces.insert(tooling::Replacement(
346 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
347 0, WhiteSpace));
348 }
349 } else if (IndentDelta < 0) {
350 std::string WhiteSpace(-IndentDelta, ' ');
351 // Check that the line is indented enough.
352 for (size_t i = 1; i < Lines.size(); ++i) {
353 if (!Lines[i].startswith(WhiteSpace))
354 return;
355 }
356 for (size_t i = 1; i < Lines.size(); ++i) {
357 Replaces.insert(tooling::Replacement(
358 SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
359 -IndentDelta, ""));
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000360 }
361 }
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000362
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000363 // Split long lines in comments.
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000364 size_t OldPrefixSize = 0;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000365 std::string NewPrefix;
366 if (Lines.size() > 1) {
367 StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000368 OldPrefixSize = CurrentPrefix.size();
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000369 NewPrefix = (IndentDelta < 0)
370 ? CurrentPrefix.substr(-IndentDelta).str()
371 : std::string(IndentDelta, ' ') + CurrentPrefix.str();
372 if (CurrentPrefix.endswith("*")) {
373 NewPrefix += " ";
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000374 ++OldPrefixSize;
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000375 }
376 } else if (Tok.Parent == 0) {
377 NewPrefix = std::string(StartColumn, ' ') + " * ";
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000378 }
379
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000380 StartColumn += 2;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000381 for (size_t i = 0; i < Lines.size(); ++i) {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +0000382 StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000383 splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
384 InPPDirective, i != Lines.size() - 1);
Alexander Kornienko547a9f522013-03-21 12:28:10 +0000385 StartColumn = NewPrefix.size();
Alexander Kornienko79d6c722013-03-15 13:42:02 +0000386 }
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000387 }
388
Manuel Klimek1998ea22013-02-20 10:15:13 +0000389 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
390 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
391 }
392
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000393 std::string getNewLineText(unsigned NewLines, unsigned Spaces,
394 unsigned WhitespaceStartColumn) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000395 std::string NewLineText;
396 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000397 unsigned Offset =
398 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000399 for (unsigned i = 0; i < NewLines; ++i) {
400 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
401 NewLineText += "\\\n";
402 Offset = 0;
403 }
404 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000405 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000406 }
407
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000408 /// \brief Structure to store a comment for later layout and alignment.
409 struct StoredComment {
410 FormatToken Tok;
411 unsigned MinColumn;
412 unsigned MaxColumn;
413 unsigned NewLines;
414 unsigned Spaces;
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000415 bool Untouchable;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000416 };
417 SmallVector<StoredComment, 16> Comments;
418 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
419
420 /// \brief Try to align all stashed comments.
421 void alignComments() {
422 unsigned MinColumn = 0;
423 unsigned MaxColumn = UINT_MAX;
424 comment_iterator Start = Comments.begin();
Alexander Kornienkodd8ed852013-03-14 16:10:54 +0000425 for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000426 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
427 alignComments(Start, I, MinColumn);
428 MinColumn = I->MinColumn;
429 MaxColumn = I->MaxColumn;
430 Start = I;
431 } else {
432 MinColumn = std::max(MinColumn, I->MinColumn);
433 MaxColumn = std::min(MaxColumn, I->MaxColumn);
434 }
435 }
436 alignComments(Start, Comments.end(), MinColumn);
437 Comments.clear();
438 }
439
440 /// \brief Put all the comments between \p I and \p E into \p Column.
441 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
442 while (I != E) {
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000443 if (!I->Untouchable) {
444 unsigned Spaces = I->Spaces + Column - I->MinColumn;
Alexander Kornienkofd433362013-03-27 17:08:02 +0000445 storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
Daniel Jasperbc0fa392013-03-22 16:25:51 +0000446 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000447 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000448 }
449 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000450
451 /// \brief Stores \p Text as the replacement for the whitespace in front of
452 /// \p Tok.
453 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000454 // Don't create a replacement, if it does not change anything.
455 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
456 Tok.WhiteSpaceLength) == Text)
457 return;
458
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000459 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
460 Tok.WhiteSpaceLength, Text));
461 }
462
463 SourceManager &SourceMgr;
464 tooling::Replacements Replaces;
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000465 const FormatStyle &Style;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000466};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000467
Daniel Jasperf7935112012-12-03 18:12:45 +0000468class UnwrappedLineFormatter {
469public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000470 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000471 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000472 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000473 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000474 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000475 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000476 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000477
Manuel Klimek1abf7892013-01-04 23:34:14 +0000478 /// \brief Formats an \c UnwrappedLine.
479 ///
480 /// \returns The column after the last token in the last line of the
481 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000482 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000483 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000484 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000485 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000486 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000487 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000488 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper97b89482013-03-13 07:49:51 +0000489 /*HasMultiParameterLine=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000490 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000491 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000492 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000493 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000494
Manuel Klimek24998102013-01-16 14:55:28 +0000495 DEBUG({
496 DebugTokenState(*State.NextToken);
497 });
498
Daniel Jaspere9de2602012-12-06 09:56:08 +0000499 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000500 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000501
Daniel Jasper4b866272013-02-01 11:00:45 +0000502 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000503 unsigned ColumnLimit = Style.ColumnLimit;
504 if (NextLine && NextLine->InPPDirective &&
505 !NextLine->First.FormatTok.HasUnescapedNewline)
506 ColumnLimit = getColumnLimit();
507 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000508 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000509 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000510 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000511 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000512 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000513
Daniel Jasperacc33662013-02-08 08:22:00 +0000514 // If the ObjC method declaration does not fit on a line, we should format
515 // it with one arg per line.
516 if (Line.Type == LT_ObjCMethodDecl)
517 State.Stack.back().BreakBeforeParameter = true;
518
Daniel Jasper4b866272013-02-01 11:00:45 +0000519 // Find best solution in solution space.
520 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 }
522
523private:
Manuel Klimek24998102013-01-16 14:55:28 +0000524 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
525 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000526 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
527 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000528 llvm::errs();
529 }
530
Daniel Jasper337816e2013-01-11 10:22:12 +0000531 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000532 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
533 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000534 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
535 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000536 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000537 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasperc238c872013-04-02 14:33:13 +0000538 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
Daniel Jaspera628c982013-04-03 13:36:17 +0000539 CallContinuation(0), VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000540
Daniel Jasperf7935112012-12-03 18:12:45 +0000541 /// \brief The position to which a specific parenthesis level needs to be
542 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000544
Daniel Jaspere9de2602012-12-06 09:56:08 +0000545 /// \brief The position of the last space on each level.
546 ///
547 /// Used e.g. to break like:
548 /// functionCall(Parameter, otherCall(
549 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000550 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000551
Daniel Jaspere9de2602012-12-06 09:56:08 +0000552 /// \brief The position the first "<<" operator encountered on each level.
553 ///
554 /// Used to align "<<" operators. 0 if no such operator has been encountered
555 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000557
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000558 /// \brief Whether a newline needs to be inserted before the block's closing
559 /// brace.
560 ///
561 /// We only want to insert a newline before the closing brace if there also
562 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000563 bool BreakBeforeClosingBrace;
564
Daniel Jasperca6623b2013-01-28 12:45:14 +0000565 /// \brief The column of a \c ? in a conditional expression;
566 unsigned QuestionColumn;
567
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000568 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
569 /// lines, in this context.
570 bool AvoidBinPacking;
571
572 /// \brief Break after the next comma (or all the commas in this context if
573 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000574 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000575
576 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000577 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000578
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000579 /// \brief The position of the colon in an ObjC method declaration/call.
580 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000581
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000582 /// \brief The start of the most recent function in a builder-type call.
583 unsigned StartOfFunctionCall;
584
Daniel Jasperc238c872013-04-02 14:33:13 +0000585 /// \brief If a nested name specifier was broken over multiple lines, this
586 /// contains the start column of the second line. Otherwise 0.
587 unsigned NestedNameSpecifierContinuation;
588
589 /// \brief If a call expression was broken over multiple lines, this
590 /// contains the start column of the second line. Otherwise 0.
591 unsigned CallContinuation;
592
Daniel Jaspera628c982013-04-03 13:36:17 +0000593 /// \brief The column of the first variable name in a variable declaration.
594 ///
595 /// Used to align further variables if necessary.
596 unsigned VariablePos;
597
Daniel Jasper337816e2013-01-11 10:22:12 +0000598 bool operator<(const ParenState &Other) const {
599 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000600 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 if (LastSpace != Other.LastSpace)
602 return LastSpace < Other.LastSpace;
603 if (FirstLessLess != Other.FirstLessLess)
604 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000605 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
606 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000607 if (QuestionColumn != Other.QuestionColumn)
608 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000609 if (AvoidBinPacking != Other.AvoidBinPacking)
610 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000611 if (BreakBeforeParameter != Other.BreakBeforeParameter)
612 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000613 if (HasMultiParameterLine != Other.HasMultiParameterLine)
614 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000615 if (ColonPos != Other.ColonPos)
616 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000617 if (StartOfFunctionCall != Other.StartOfFunctionCall)
618 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000619 if (NestedNameSpecifierContinuation !=
620 Other.NestedNameSpecifierContinuation)
621 return NestedNameSpecifierContinuation <
622 Other.NestedNameSpecifierContinuation;
623 if (CallContinuation != Other.CallContinuation)
624 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000625 if (VariablePos != Other.VariablePos)
626 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000627 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000628 }
629 };
630
631 /// \brief The current state when indenting a unwrapped line.
632 ///
633 /// As the indenting tries different combinations this is copied by value.
634 struct LineState {
635 /// \brief The number of used columns in the current line.
636 unsigned Column;
637
638 /// \brief The token that needs to be next formatted.
639 const AnnotatedToken *NextToken;
640
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000641 /// \brief \c true if this line contains a continued for-loop section.
642 bool LineContainsContinuedForLoopSection;
643
Daniel Jasper400adc62013-02-08 15:28:42 +0000644 /// \brief The level of nesting inside (), [], <> and {}.
645 unsigned ParenLevel;
646
Daniel Jasper40c36c52013-02-18 11:05:07 +0000647 /// \brief The \c ParenLevel at the start of this line.
648 unsigned StartOfLineLevel;
649
Manuel Klimek02f640a2013-02-20 15:25:48 +0000650 /// \brief The start column of the string literal, if we're in a string
651 /// literal sequence, 0 otherwise.
652 unsigned StartOfStringLiteral;
653
Daniel Jasper337816e2013-01-11 10:22:12 +0000654 /// \brief A stack keeping track of properties applying to parenthesis
655 /// levels.
656 std::vector<ParenState> Stack;
657
658 /// \brief Comparison operator to be able to used \c LineState in \c map.
659 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000660 if (NextToken != Other.NextToken)
661 return NextToken < Other.NextToken;
662 if (Column != Other.Column)
663 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000664 if (LineContainsContinuedForLoopSection !=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000665 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000666 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000667 if (ParenLevel != Other.ParenLevel)
668 return ParenLevel < Other.ParenLevel;
669 if (StartOfLineLevel != Other.StartOfLineLevel)
670 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000671 if (StartOfStringLiteral != Other.StartOfStringLiteral)
672 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000673 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000674 }
675 };
676
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000677 /// \brief Appends the next token to \p State and updates information
678 /// necessary for indentation.
679 ///
680 /// Puts the token on the current line if \p Newline is \c true and adds a
681 /// line break and necessary indentation otherwise.
682 ///
683 /// If \p DryRun is \c false, also creates and stores the required
684 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000685 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000686 const AnnotatedToken &Current = *State.NextToken;
687 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000688
Daniel Jasper291f9362013-03-20 15:58:10 +0000689 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000690 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
691 State.NextToken->FormatTok.TokenLength;
692 if (State.NextToken->Children.empty())
693 State.NextToken = NULL;
694 else
695 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000696 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000697 }
698
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000699 // If we are continuing an expression, we want to indent an extra 4 spaces.
700 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000701 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000702 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000703 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000704 if (Current.is(tok::r_brace)) {
705 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000706 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000707 State.StartOfStringLiteral != 0) {
708 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000709 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000710 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000711 State.Stack.back().FirstLessLess != 0) {
712 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000713 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000714 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
715 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000716 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000717 } else {
718 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
719 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000720 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000721 if (State.Stack.back().CallContinuation == 0) {
722 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000723 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000724 } else {
725 State.Column = State.Stack.back().CallContinuation;
726 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000727 } else if (Current.Type == TT_ConditionalExpr) {
728 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000729 } else if (Previous.is(tok::comma) &&
730 State.Stack.back().VariablePos != 0) {
731 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000732 } else if (Previous.ClosesTemplateDeclaration ||
733 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000734 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000735 } else if (Current.Type == TT_ObjCSelectorName) {
736 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
737 State.Column =
738 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
739 } else {
740 State.Column = State.Stack.back().Indent;
741 State.Stack.back().ColonPos =
742 State.Column + Current.FormatTok.TokenLength;
743 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000744 } else if (Current.Type == TT_StartOfName || Current.is(tok::question) ||
745 Previous.is(tok::equal) || isComparison(Previous) ||
746 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000747 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000748 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000749 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000750 // Ensure that we fall back to indenting 4 spaces instead of just
751 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000752 if (State.Column == FirstIndent)
753 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000754 }
755
Daniel Jasper54a86022013-02-15 11:07:25 +0000756 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000757 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000758 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000759 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000760 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000761
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000762 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000763 unsigned NewLines = 1;
764 if (Current.Type == TT_LineComment)
765 NewLines =
766 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
767 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000768 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000769 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000770 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000771 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000772 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000773 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000774 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000775
Daniel Jasper400adc62013-02-08 15:28:42 +0000776 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000777 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000778
779 // Any break on this level means that the parent level has been broken
780 // and we need to avoid bin packing there.
781 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
782 State.Stack[i].BreakBeforeParameter = true;
783 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000784 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000785 State.Stack.back().BreakBeforeParameter = true;
786
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000787 // If we break after {, we should also break before the corresponding }.
788 if (Previous.is(tok::l_brace))
789 State.Stack.back().BreakBeforeClosingBrace = true;
790
791 if (State.Stack.back().AvoidBinPacking) {
792 // If we are breaking after '(', '{', '<', this is not bin packing
793 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000794 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000795 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
796 Line.MustBeDeclaration))
797 State.Stack.back().BreakBeforeParameter = true;
798 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000799 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000800 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000801 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
802 State.Stack.back().VariablePos == 0) {
803 State.Stack.back().VariablePos = State.Column;
804 // Move over * and & if they are bound to the variable name.
805 const AnnotatedToken *Tok = &Previous;
806 while (Tok &&
807 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
808 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
809 if (Tok->SpacesRequiredBefore != 0)
810 break;
811 Tok = Tok->Parent;
812 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000813 if (Previous.PartOfMultiVariableDeclStmt)
814 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
815 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000816
Daniel Jaspereef30492013-02-11 12:36:37 +0000817 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000818
Daniel Jasperf7935112012-12-03 18:12:45 +0000819 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000820 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000821
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000822 if (Current.Type == TT_ObjCSelectorName &&
823 State.Stack.back().ColonPos == 0) {
824 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000825 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000826 State.Stack.back().ColonPos =
827 State.Stack.back().Indent + Current.LongestObjCSelectorName;
828 else
829 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000830 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000831 }
832
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000833 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000834 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000835 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000836 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000837 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000838 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000839
Daniel Jaspere9de2602012-12-06 09:56:08 +0000840 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000841 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000842 // Treat the condition inside an if as if it was a second function
843 // parameter, i.e. let nested calls have an indent of 4.
844 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000845 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000846 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000847 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000848 Previous.Type == TT_ConditionalExpr ||
849 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000850 getPrecedence(Previous) != prec::Assignment)
851 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000852 else if (Previous.Type == TT_InheritanceColon)
853 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000854 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000855 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000856 Previous.Type == TT_TemplateOpener))
857 // If this function has multiple parameters, indent nested calls from
858 // the start of the first parameter.
859 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000861
Manuel Klimek1998ea22013-02-20 10:15:13 +0000862 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000863 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000864
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000865 /// \brief Mark the next token as consumed in \p State and modify its stacks
866 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000867 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000869 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000870
Daniel Jaspereead02b2013-02-14 08:42:54 +0000871 if (Current.Type == TT_InheritanceColon)
872 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000873 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
874 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000875 if (Current.is(tok::question))
876 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000877 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000878 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
879 State.Stack.back().StartOfFunctionCall =
880 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000881 if (Current.Type == TT_CtorInitializerColon) {
882 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
883 State.Stack.back().AvoidBinPacking = true;
884 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000885 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000886
887 // In ObjC method declaration we align on the ":" of parameters, but we need
888 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000889 if (Current.Type == TT_ObjCMethodSpecifier)
890 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000891
Daniel Jasper400adc62013-02-08 15:28:42 +0000892 // Insert scopes created by fake parenthesis.
893 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
894 ParenState NewParenState = State.Stack.back();
895 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000896 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000897 State.Stack.push_back(NewParenState);
898 }
899
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000900 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000901 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000902 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000904 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000905 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000906 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000907 NewIndent = 2 + State.Stack.back().LastSpace;
908 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000909 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000910 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
911 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000912 AvoidBinPacking =
913 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000914 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000915 State.Stack.push_back(
916 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
917 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000918 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000919 }
920
Daniel Jasperacc33662013-02-08 08:22:00 +0000921 // If this '[' opens an ObjC call, determine whether all parameters fit into
922 // one line and put one per line if they don't.
923 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
924 Current.MatchingParen != NULL) {
925 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
926 State.Stack.back().BreakBeforeParameter = true;
927 }
928
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000929 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000930 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000931 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
933 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000934 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000935 --State.ParenLevel;
936 }
937
938 // Remove scopes created by fake parenthesis.
939 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000940 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000941 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000942 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000943 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000944
Manuel Klimek0c915712013-02-20 15:32:58 +0000945 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000946 State.StartOfStringLiteral = State.Column;
947 } else if (Current.isNot(tok::comment)) {
948 State.StartOfStringLiteral = 0;
949 }
950
Manuel Klimek1998ea22013-02-20 10:15:13 +0000951 State.Column += Current.FormatTok.TokenLength;
952
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000953 if (State.NextToken->Children.empty())
954 State.NextToken = NULL;
955 else
956 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000957
Manuel Klimek1998ea22013-02-20 10:15:13 +0000958 return breakProtrudingToken(Current, State, DryRun);
959 }
960
961 /// \brief If the current token sticks out over the end of the line, break
962 /// it if possible.
963 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
964 bool DryRun) {
965 if (Current.isNot(tok::string_literal))
966 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000967 // Only break up default narrow strings.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000968 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
969 if (!LiteralData || *LiteralData != '"')
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000970 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000971
972 unsigned Penalty = 0;
973 unsigned TailOffset = 0;
974 unsigned TailLength = Current.FormatTok.TokenLength;
975 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
976 unsigned OffsetFromStart = 0;
977 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000978 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000979 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000980 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000981 StringRef::size_type SplitPoint = getSplitPoint(
982 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000983 if (SplitPoint == StringRef::npos)
984 break;
985 assert(SplitPoint != 0);
986 // +2, because 'Text' starts after the opening quotes, and does not
987 // include the closing quote we need to insert.
988 unsigned WhitespaceStartColumn =
989 StartColumn + OffsetFromStart + SplitPoint + 2;
990 State.Stack.back().LastSpace = StartColumn;
991 if (!DryRun) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000992 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
993 0, "\"", "\"", Line.InPPDirective, StartColumn,
994 WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000995 }
996 TailOffset += SplitPoint + 1;
997 TailLength -= SplitPoint + 1;
998 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000999 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +00001000 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
1001 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +00001002 }
1003 State.Column = StartColumn + TailLength;
1004 return Penalty;
1005 }
1006
1007 StringRef::size_type
1008 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +00001009 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +00001010 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001011 return SpaceOffset;
1012 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +00001013 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001014 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001015 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
1016 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001017 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001018 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +00001019 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +00001020 }
1021
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001022 StringRef::size_type
1023 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
1024 StringRef::size_type NextEscape = Text.find('\\');
1025 while (NextEscape != StringRef::npos && NextEscape < Offset) {
1026 StringRef::size_type SequenceLength =
1027 getEscapeSequenceLength(Text.substr(NextEscape));
1028 if (Offset < NextEscape + SequenceLength)
1029 return NextEscape;
1030 NextEscape = Text.find('\\', NextEscape + SequenceLength);
1031 }
1032 return Offset;
1033 }
1034
1035 unsigned getEscapeSequenceLength(StringRef Text) {
1036 assert(Text[0] == '\\');
1037 if (Text.size() < 2)
1038 return 1;
1039
1040 switch (Text[1]) {
1041 case 'u':
1042 return 6;
1043 case 'U':
1044 return 10;
1045 case 'x':
1046 return getHexLength(Text);
1047 default:
1048 if (Text[1] >= '0' && Text[1] <= '7')
1049 return getOctalLength(Text);
1050 return 2;
1051 }
1052 }
1053
1054 unsigned getHexLength(StringRef Text) {
1055 unsigned I = 2; // Point after '\x'.
1056 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
1057 (Text[I] >= 'a' && Text[I] <= 'f') ||
1058 (Text[I] >= 'A' && Text[I] <= 'F'))) {
1059 ++I;
1060 }
1061 return I;
1062 }
1063
1064 unsigned getOctalLength(StringRef Text) {
1065 unsigned I = 1;
1066 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
1067 ++I;
1068 }
1069 return I;
1070 }
1071
Daniel Jasper2df93312013-01-09 10:16:05 +00001072 unsigned getColumnLimit() {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +00001073 return calculateColumnLimit(Style, Line.InPPDirective);
Daniel Jasper2df93312013-01-09 10:16:05 +00001074 }
1075
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001076 /// \brief An edge in the solution space from \c Previous->State to \c State,
1077 /// inserting a newline dependent on the \c NewLine.
1078 struct StateNode {
1079 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001080 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001081 LineState State;
1082 bool NewLine;
1083 StateNode *Previous;
1084 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001085
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001086 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1087 ///
1088 /// In case of equal penalties, we want to prefer states that were inserted
1089 /// first. During state generation we make sure that we insert states first
1090 /// that break the line as late as possible.
1091 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1092
1093 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1094 /// \c State has the given \c OrderedPenalty.
1095 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1096
1097 /// \brief The BFS queue type.
1098 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1099 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001100
1101 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001102 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001103 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1104 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1105 /// find the shortest path (the one with lowest penalty) from \p InitialState
1106 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001107 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001108 std::set<LineState> Seen;
1109
Daniel Jasper4b866272013-02-01 11:00:45 +00001110 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001111 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001112 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1113 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1114 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001115
1116 // While not empty, take first element and follow edges.
1117 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001118 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001119 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001120 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001121 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001122 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001123 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001124 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001125
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001126 if (!Seen.insert(Node->State).second)
1127 // State already examined with lower penalty.
1128 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001129
Manuel Klimekaf491072013-02-13 10:54:19 +00001130 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1131 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001132 }
1133
1134 if (Queue.empty())
1135 // We were unable to find a solution, do nothing.
1136 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 return 0;
1138
Daniel Jasper4b866272013-02-01 11:00:45 +00001139 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001140 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001141 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +00001142
Daniel Jasper4b866272013-02-01 11:00:45 +00001143 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001144 return Queue.top().second->State.Column;
1145 }
1146
1147 void reconstructPath(LineState &State, StateNode *Current) {
1148 // FIXME: This recursive implementation limits the possible number
1149 // of tokens per line if compiled into a binary with small stack space.
1150 // To become more independent of stack frame limitations we would need
1151 // to also change the TokenAnnotator.
1152 if (Current->Previous == NULL)
1153 return;
1154 reconstructPath(State, Current->Previous);
1155 DEBUG({
1156 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +00001157 llvm::errs()
1158 << "Penalty for splitting before "
1159 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1160 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001161 }
1162 });
1163 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +00001164 }
1165
Manuel Klimekaf491072013-02-13 10:54:19 +00001166 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001167 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001168 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001169 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001170 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1171 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001172 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001173 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001174 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001175 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001176 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001177 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1178
1179 StateNode *Node = new (Allocator.Allocate())
1180 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001181 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001182 if (Node->State.Column > getColumnLimit()) {
1183 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001184 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001185 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001186
1187 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1188 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001189 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001190
Daniel Jasper4b866272013-02-01 11:00:45 +00001191 /// \brief Returns \c true, if a line break after \p State is allowed.
1192 bool canBreak(const LineState &State) {
1193 if (!State.NextToken->CanBreakBefore &&
1194 !(State.NextToken->is(tok::r_brace) &&
1195 State.Stack.back().BreakBeforeClosingBrace))
1196 return false;
1197 // Trying to insert a parameter on a new line if there are already more than
1198 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +00001199 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001200 State.Stack.back().AvoidBinPacking)
1201 return false;
1202 return true;
1203 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001204
Daniel Jasper4b866272013-02-01 11:00:45 +00001205 /// \brief Returns \c true, if a line break after \p State is mandatory.
1206 bool mustBreak(const LineState &State) {
1207 if (State.NextToken->MustBreakBefore)
1208 return true;
1209 if (State.NextToken->is(tok::r_brace) &&
1210 State.Stack.back().BreakBeforeClosingBrace)
1211 return true;
1212 if (State.NextToken->Parent->is(tok::semi) &&
1213 State.LineContainsContinuedForLoopSection)
1214 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001215 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +00001216 State.NextToken->is(tok::question) ||
1217 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001218 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +00001219 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +00001220 State.NextToken->isNot(tok::r_paren) &&
1221 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001222 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +00001223 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1224 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001225 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001226 State.NextToken->LongestObjCSelectorName == 0 &&
1227 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001228 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001229 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1230 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001231 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001232 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001233 if (State.NextToken->Type == TT_InlineASMColon)
1234 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +00001235 // This prevents breaks like:
1236 // ...
1237 // SomeParameter, OtherParameter).DoSomething(
1238 // ...
1239 // As they hide "DoSomething" and generally bad for readability.
1240 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1241 getRemainingLength(State) + State.Column > getColumnLimit() &&
1242 State.ParenLevel < State.StartOfLineLevel)
1243 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001244 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245 }
1246
Daniel Jasper9b334242013-03-15 14:57:30 +00001247 // Returns the total number of columns required for the remaining tokens.
1248 unsigned getRemainingLength(const LineState &State) {
1249 if (State.NextToken && State.NextToken->Parent)
1250 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1251 return 0;
1252 }
1253
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 FormatStyle Style;
1255 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001256 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001257 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001258 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001259 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001260
1261 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1262 QueueType Queue;
1263 // Increasing count of \c StateNode items we have created. This is used
1264 // to create a deterministic order independent of the container.
1265 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001266};
1267
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001268class LexerBasedFormatTokenSource : public FormatTokenSource {
1269public:
1270 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001271 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001272 IdentTable(Lex.getLangOpts()) {
1273 Lex.SetKeepWhitespaceMode(true);
1274 }
1275
1276 virtual FormatToken getNextToken() {
1277 if (GreaterStashed) {
1278 FormatTok.NewlinesBefore = 0;
1279 FormatTok.WhiteSpaceStart =
1280 FormatTok.Tok.getLocation().getLocWithOffset(1);
1281 FormatTok.WhiteSpaceLength = 0;
1282 GreaterStashed = false;
1283 return FormatTok;
1284 }
1285
1286 FormatTok = FormatToken();
1287 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001288 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001289 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001290 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1291 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001292
1293 // Consume and record whitespace until we find a significant token.
1294 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001295 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001296 if (Newlines > 0)
1297 FormatTok.LastNewlineOffset =
1298 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001299 unsigned EscapedNewlines = Text.count("\\\n");
1300 FormatTok.NewlinesBefore += Newlines;
1301 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001302 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1303
1304 if (FormatTok.Tok.is(tok::eof))
1305 return FormatTok;
1306 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001307 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001308 }
Manuel Klimekef920692013-01-07 07:56:50 +00001309
1310 // Now FormatTok is the next non-whitespace token.
1311 FormatTok.TokenLength = Text.size();
1312
Manuel Klimek1abf7892013-01-04 23:34:14 +00001313 // In case the token starts with escaped newlines, we want to
1314 // take them into account as whitespace - this pattern is quite frequent
1315 // in macro definitions.
1316 // FIXME: What do we want to do with other escaped spaces, and escaped
1317 // spaces or newlines in the middle of tokens?
1318 // FIXME: Add a more explicit test.
1319 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001320 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001321 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001322 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001323 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001324 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001325 }
1326
1327 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001328 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001329 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001330 FormatTok.Tok.setKind(Info.getTokenID());
1331 }
1332
1333 if (FormatTok.Tok.is(tok::greatergreater)) {
1334 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001335 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001336 GreaterStashed = true;
1337 }
1338
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001339 // If we reformat comments, we remove trailing whitespace. Update the length
1340 // accordingly.
1341 if (FormatTok.Tok.is(tok::comment))
1342 FormatTok.TokenLength = Text.rtrim().size();
1343
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001344 return FormatTok;
1345 }
1346
Nico Weber29f9dea2013-02-11 15:32:15 +00001347 IdentifierTable &getIdentTable() { return IdentTable; }
1348
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001349private:
1350 FormatToken FormatTok;
1351 bool GreaterStashed;
1352 Lexer &Lex;
1353 SourceManager &SourceMgr;
1354 IdentifierTable IdentTable;
1355
1356 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001357 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001358 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1359 Tok.getLength());
1360 }
1361};
1362
Daniel Jasperf7935112012-12-03 18:12:45 +00001363class Formatter : public UnwrappedLineConsumer {
1364public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001365 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1366 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001367 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001368 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001369 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001370
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001371 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001372
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001373 tooling::Replacements format() {
1374 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1375 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1376 StructuralError = Parser.parse();
1377 unsigned PreviousEndOfLineColumn = 0;
1378 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1379 Tokens.getIdentTable().get("in"));
1380 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1381 Annotator.annotate(AnnotatedLines[i]);
1382 }
1383 deriveLocalStyle();
1384 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1385 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper0f8ed9e2013-03-13 15:53:12 +00001386
1387 // Adapt level to the next line if this is a comment.
1388 // FIXME: Can/should this be done in the UnwrappedLineParser?
1389 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1390 AnnotatedLines[i].First.Children.empty() &&
1391 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1392 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001393 }
1394 std::vector<int> IndentForLevel;
1395 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001396 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001397 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1398 E = AnnotatedLines.end();
1399 I != E; ++I) {
1400 const AnnotatedLine &TheLine = *I;
1401 const FormatToken &FirstTok = TheLine.First.FormatTok;
1402 int Offset = getIndentOffset(TheLine.First);
1403 while (IndentForLevel.size() <= TheLine.Level)
1404 IndentForLevel.push_back(-1);
1405 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001406 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001407 if (TheLine.First.is(tok::eof)) {
1408 if (PreviousLineWasTouched) {
1409 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1410 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001411 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001412 }
1413 } else if (TheLine.Type != LT_Invalid &&
1414 (WasMoved || touchesLine(TheLine))) {
1415 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1416 unsigned Indent = LevelIndent;
1417 if (static_cast<int>(Indent) + Offset >= 0)
1418 Indent += Offset;
1419 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001420 Indent = LevelIndent =
1421 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001422 } else {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001423 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1424 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001425 }
1426 tryFitMultipleLinesInOne(Indent, I, E);
1427 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1428 TheLine.First, Whitespaces,
1429 StructuralError);
1430 PreviousEndOfLineColumn =
1431 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1432 IndentForLevel[TheLine.Level] = LevelIndent;
1433 PreviousLineWasTouched = true;
1434 } else {
1435 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1436 unsigned Indent =
1437 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1438 unsigned LevelIndent = Indent;
1439 if (static_cast<int>(LevelIndent) - Offset >= 0)
1440 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001441 if (TheLine.First.isNot(tok::comment))
1442 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001443
1444 // Remove trailing whitespace of the previous line if it was touched.
1445 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001446 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1447 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001448 }
1449 // If we did not reformat this unwrapped line, the column at the end of
1450 // the last token is unchanged - thus, we can calculate the end of the
1451 // last token.
1452 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1453 PreviousEndOfLineColumn =
1454 SourceMgr.getSpellingColumnNumber(LastLoc) +
1455 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1456 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001457 if (TheLine.Last->is(tok::comment))
1458 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1459 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001460 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001461 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001462 }
1463 return Whitespaces.generateReplacements();
1464 }
1465
1466private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001467 void deriveLocalStyle() {
1468 unsigned CountBoundToVariable = 0;
1469 unsigned CountBoundToType = 0;
1470 bool HasCpp03IncompatibleFormat = false;
1471 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1472 if (AnnotatedLines[i].First.Children.empty())
1473 continue;
1474 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1475 while (!Tok->Children.empty()) {
1476 if (Tok->Type == TT_PointerOrReference) {
1477 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1478 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1479 if (SpacesBefore && !SpacesAfter)
1480 ++CountBoundToVariable;
1481 else if (!SpacesBefore && SpacesAfter)
1482 ++CountBoundToType;
1483 }
1484
Daniel Jasper400adc62013-02-08 15:28:42 +00001485 if (Tok->Type == TT_TemplateCloser &&
1486 Tok->Parent->Type == TT_TemplateCloser &&
1487 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001488 HasCpp03IncompatibleFormat = true;
1489 Tok = &Tok->Children[0];
1490 }
1491 }
1492 if (Style.DerivePointerBinding) {
1493 if (CountBoundToType > CountBoundToVariable)
1494 Style.PointerBindsToType = true;
1495 else if (CountBoundToType < CountBoundToVariable)
1496 Style.PointerBindsToType = false;
1497 }
1498 if (Style.Standard == FormatStyle::LS_Auto) {
1499 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1500 : FormatStyle::LS_Cpp03;
1501 }
1502 }
1503
Manuel Klimekb95f5452013-02-08 17:38:27 +00001504 /// \brief Get the indent of \p Level from \p IndentForLevel.
1505 ///
1506 /// \p IndentForLevel must contain the indent for the level \c l
1507 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1508 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001509 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001510 if (IndentForLevel[Level] != -1)
1511 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001512 if (Level == 0)
1513 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001514 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001515 }
1516
1517 /// \brief Get the offset of the line relatively to the level.
1518 ///
1519 /// For example, 'public:' labels in classes are offset by 1 or 2
1520 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001521 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001522 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001523 return Style.AccessModifierOffset;
1524 return 0;
1525 }
1526
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001527 /// \brief Tries to merge lines into one.
1528 ///
1529 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1530 /// if possible; note that \c I will be incremented when lines are merged.
1531 ///
1532 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001533 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001534 std::vector<AnnotatedLine>::iterator &I,
1535 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001536 // We can never merge stuff if there are trailing line comments.
1537 if (I->Last->Type == TT_LineComment)
1538 return;
1539
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001540 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001541 // If we already exceed the column limit, we set 'Limit' to 0. The different
1542 // tryMerge..() functions can then decide whether to still do merging.
1543 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001544
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001545 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001546 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001547
Daniel Jasper25837aa2013-01-14 14:14:23 +00001548 if (I->Last->is(tok::l_brace)) {
1549 tryMergeSimpleBlock(I, E, Limit);
1550 } else if (I->First.is(tok::kw_if)) {
1551 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001552 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1553 I->First.FormatTok.IsFirst)) {
1554 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001555 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001556 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001557 }
1558
Daniel Jasper39825ea2013-01-14 15:40:57 +00001559 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1560 std::vector<AnnotatedLine>::iterator E,
1561 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001562 if (Limit == 0)
1563 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001564 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001565 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1566 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001567 if (I + 2 != E && (I + 2)->InPPDirective &&
1568 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1569 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001570 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001571 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001572 join(Line, *(++I));
1573 }
1574
Daniel Jasper25837aa2013-01-14 14:14:23 +00001575 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1576 std::vector<AnnotatedLine>::iterator E,
1577 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001578 if (Limit == 0)
1579 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001580 if (!Style.AllowShortIfStatementsOnASingleLine)
1581 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001582 if ((I + 1)->InPPDirective != I->InPPDirective ||
1583 ((I + 1)->InPPDirective &&
1584 (I + 1)->First.FormatTok.HasUnescapedNewline))
1585 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001586 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001587 if (Line.Last->isNot(tok::r_paren))
1588 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001589 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001590 return;
1591 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1592 return;
1593 // Only inline simple if's (no nested if or else).
1594 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1595 return;
1596 join(Line, *(++I));
1597 }
1598
1599 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001600 std::vector<AnnotatedLine>::iterator E,
1601 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001602 // First, check that the current line allows merging. This is the case if
1603 // we're not in a control flow statement and the last token is an opening
1604 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001605 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001606 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1607 tok::kw_else, tok::kw_try, tok::kw_catch,
1608 tok::kw_for,
1609 // This gets rid of all ObjC @ keywords and methods.
1610 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001611 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001612
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001613 AnnotatedToken *Tok = &(I + 1)->First;
1614 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001615 !Tok->MustBreakBefore) {
1616 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001617 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001618 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001619 join(Line, *(I + 1));
1620 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001621 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001622 // Check that we still have three lines and they fit into the limit.
1623 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1624 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001625 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001626
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001627 // Second, check that the next line does not contain any braces - if it
1628 // does, readability declines when putting it into a single line.
1629 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1630 return;
1631 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001632 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001633 return;
1634 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1635 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001636
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001637 // Last, check that the third line contains a single closing brace.
1638 Tok = &(I + 2)->First;
1639 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1640 Tok->MustBreakBefore)
1641 return;
1642
1643 join(Line, *(I + 1));
1644 join(Line, *(I + 2));
1645 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001646 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001647 }
1648
1649 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1650 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001651 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1652 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001653 }
1654
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001655 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001656 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001657 A.Last->Children.push_back(B.First);
1658 while (!A.Last->Children.empty()) {
1659 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001660 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001661 A.Last = &A.Last->Children[0];
1662 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001663 }
1664
Daniel Jasper97b89482013-03-13 07:49:51 +00001665 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001666 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1667 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1668 Ranges[i].getBegin()) &&
1669 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1670 Range.getBegin()))
1671 return true;
1672 }
1673 return false;
1674 }
1675
1676 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001677 const FormatToken *First = &TheLine.First.FormatTok;
1678 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001679 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001680 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1681 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001682 return touchesRanges(LineRange);
1683 }
1684
1685 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1686 const FormatToken *First = &TheLine.First.FormatTok;
1687 CharSourceRange LineRange = CharSourceRange::getCharRange(
1688 First->WhiteSpaceStart,
1689 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1690 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001691 }
1692
1693 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001694 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001695 }
1696
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001697 /// \brief Add a new line and the required indent before the first Token
1698 /// of the \c UnwrappedLine if there was no structural parsing error.
1699 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001700 void formatFirstToken(const AnnotatedToken &RootToken,
1701 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001702 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001703 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001704
Daniel Jasperbbc84152013-01-29 11:27:30 +00001705 unsigned Newlines =
1706 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001707 if (Newlines == 0 && !Tok.IsFirst)
1708 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001709
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001710 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001711 // Insert extra new line before access specifiers.
1712 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1713 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1714 ++Newlines;
1715
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001716 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001717 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001718 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001719 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001720 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001721 }
1722
Alexander Kornienko116ba682013-01-14 11:34:14 +00001723 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001724 FormatStyle Style;
1725 Lexer &Lex;
1726 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001727 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001728 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001729 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001730 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001731};
1732
Daniel Jasperbbc84152013-01-29 11:27:30 +00001733tooling::Replacements
1734reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1735 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001736 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001737 OwningPtr<DiagnosticConsumer> DiagPrinter;
1738 if (DiagClient == 0) {
1739 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1740 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1741 DiagClient = DiagPrinter.get();
1742 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001743 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001744 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001745 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001746 Diagnostics.setSourceManager(&SourceMgr);
1747 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001748 return formatter.format();
1749}
1750
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001751LangOptions getFormattingLangOpts() {
1752 LangOptions LangOpts;
1753 LangOpts.CPlusPlus = 1;
1754 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001755 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001756 LangOpts.Bool = 1;
1757 LangOpts.ObjC1 = 1;
1758 LangOpts.ObjC2 = 1;
1759 return LangOpts;
1760}
1761
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001762} // namespace format
1763} // namespace clang