blob: 79619bbcbc2305a3a22dca059dde33a568feeb2c [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 Jasper38c11ce2013-01-29 11:21:01 +0000490 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000491 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000492 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000493 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000494 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000495
Manuel Klimek24998102013-01-16 14:55:28 +0000496 DEBUG({
497 DebugTokenState(*State.NextToken);
498 });
499
Daniel Jaspere9de2602012-12-06 09:56:08 +0000500 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000501 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000502
Daniel Jasper4b866272013-02-01 11:00:45 +0000503 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000504 unsigned ColumnLimit = Style.ColumnLimit;
505 if (NextLine && NextLine->InPPDirective &&
506 !NextLine->First.FormatTok.HasUnescapedNewline)
507 ColumnLimit = getColumnLimit();
508 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000509 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000510 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000511 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000512 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000513 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000514
Daniel Jasperacc33662013-02-08 08:22:00 +0000515 // If the ObjC method declaration does not fit on a line, we should format
516 // it with one arg per line.
517 if (Line.Type == LT_ObjCMethodDecl)
518 State.Stack.back().BreakBeforeParameter = true;
519
Daniel Jasper4b866272013-02-01 11:00:45 +0000520 // Find best solution in solution space.
521 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 }
523
524private:
Manuel Klimek24998102013-01-16 14:55:28 +0000525 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
526 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000527 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
528 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000529 llvm::errs();
530 }
531
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000533 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
534 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000535 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
536 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000537 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000538 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasperc238c872013-04-02 14:33:13 +0000539 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
540 CallContinuation(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000541
Daniel Jasperf7935112012-12-03 18:12:45 +0000542 /// \brief The position to which a specific parenthesis level needs to be
543 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000545
Daniel Jaspere9de2602012-12-06 09:56:08 +0000546 /// \brief The position of the last space on each level.
547 ///
548 /// Used e.g. to break like:
549 /// functionCall(Parameter, otherCall(
550 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000551 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000552
Daniel Jaspere9de2602012-12-06 09:56:08 +0000553 /// \brief The position the first "<<" operator encountered on each level.
554 ///
555 /// Used to align "<<" operators. 0 if no such operator has been encountered
556 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000557 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000558
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000559 /// \brief Whether a newline needs to be inserted before the block's closing
560 /// brace.
561 ///
562 /// We only want to insert a newline before the closing brace if there also
563 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 bool BreakBeforeClosingBrace;
565
Daniel Jasperca6623b2013-01-28 12:45:14 +0000566 /// \brief The column of a \c ? in a conditional expression;
567 unsigned QuestionColumn;
568
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000569 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
570 /// lines, in this context.
571 bool AvoidBinPacking;
572
573 /// \brief Break after the next comma (or all the commas in this context if
574 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000575 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000576
577 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000578 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000579
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000580 /// \brief The position of the colon in an ObjC method declaration/call.
581 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000582
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000583 /// \brief The start of the most recent function in a builder-type call.
584 unsigned StartOfFunctionCall;
585
Daniel Jasperc238c872013-04-02 14:33:13 +0000586 /// \brief If a nested name specifier was broken over multiple lines, this
587 /// contains the start column of the second line. Otherwise 0.
588 unsigned NestedNameSpecifierContinuation;
589
590 /// \brief If a call expression was broken over multiple lines, this
591 /// contains the start column of the second line. Otherwise 0.
592 unsigned CallContinuation;
593
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 bool operator<(const ParenState &Other) const {
595 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000596 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000597 if (LastSpace != Other.LastSpace)
598 return LastSpace < Other.LastSpace;
599 if (FirstLessLess != Other.FirstLessLess)
600 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000601 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
602 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000603 if (QuestionColumn != Other.QuestionColumn)
604 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000605 if (AvoidBinPacking != Other.AvoidBinPacking)
606 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000607 if (BreakBeforeParameter != Other.BreakBeforeParameter)
608 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000609 if (HasMultiParameterLine != Other.HasMultiParameterLine)
610 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000611 if (ColonPos != Other.ColonPos)
612 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000613 if (StartOfFunctionCall != Other.StartOfFunctionCall)
614 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000615 if (NestedNameSpecifierContinuation !=
616 Other.NestedNameSpecifierContinuation)
617 return NestedNameSpecifierContinuation <
618 Other.NestedNameSpecifierContinuation;
619 if (CallContinuation != Other.CallContinuation)
620 return CallContinuation < Other.CallContinuation;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000621 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000622 }
623 };
624
625 /// \brief The current state when indenting a unwrapped line.
626 ///
627 /// As the indenting tries different combinations this is copied by value.
628 struct LineState {
629 /// \brief The number of used columns in the current line.
630 unsigned Column;
631
632 /// \brief The token that needs to be next formatted.
633 const AnnotatedToken *NextToken;
634
Daniel Jasperbbc84152013-01-29 11:27:30 +0000635 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000636 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000637 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000638 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000639
640 /// \brief \c true if this line contains a continued for-loop section.
641 bool LineContainsContinuedForLoopSection;
642
Daniel Jasper400adc62013-02-08 15:28:42 +0000643 /// \brief The level of nesting inside (), [], <> and {}.
644 unsigned ParenLevel;
645
Daniel Jasper40c36c52013-02-18 11:05:07 +0000646 /// \brief The \c ParenLevel at the start of this line.
647 unsigned StartOfLineLevel;
648
Manuel Klimek02f640a2013-02-20 15:25:48 +0000649 /// \brief The start column of the string literal, if we're in a string
650 /// literal sequence, 0 otherwise.
651 unsigned StartOfStringLiteral;
652
Daniel Jasper337816e2013-01-11 10:22:12 +0000653 /// \brief A stack keeping track of properties applying to parenthesis
654 /// levels.
655 std::vector<ParenState> Stack;
656
657 /// \brief Comparison operator to be able to used \c LineState in \c map.
658 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000659 if (NextToken != Other.NextToken)
660 return NextToken < Other.NextToken;
661 if (Column != Other.Column)
662 return Column < Other.Column;
663 if (VariablePos != Other.VariablePos)
664 return VariablePos < Other.VariablePos;
665 if (LineContainsContinuedForLoopSection !=
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000666 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000667 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000668 if (ParenLevel != Other.ParenLevel)
669 return ParenLevel < Other.ParenLevel;
670 if (StartOfLineLevel != Other.StartOfLineLevel)
671 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000672 if (StartOfStringLiteral != Other.StartOfStringLiteral)
673 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000674 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000675 }
676 };
677
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000678 /// \brief Appends the next token to \p State and updates information
679 /// necessary for indentation.
680 ///
681 /// Puts the token on the current line if \p Newline is \c true and adds a
682 /// line break and necessary indentation otherwise.
683 ///
684 /// If \p DryRun is \c false, also creates and stores the required
685 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000686 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000687 const AnnotatedToken &Current = *State.NextToken;
688 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000689
Daniel Jasper291f9362013-03-20 15:58:10 +0000690 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000691 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
692 State.NextToken->FormatTok.TokenLength;
693 if (State.NextToken->Children.empty())
694 State.NextToken = NULL;
695 else
696 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000697 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000698 }
699
Daniel Jasperc238c872013-04-02 14:33:13 +0000700 unsigned IndentedFurther =
701 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)) {
714 State.Column = IndentedFurther;
715 if (State.Stack.back().NestedNameSpecifierContinuation == 0)
716 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
717 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
718 } else if (Current.isOneOf(tok::period, tok::arrow)) {
719 State.Column = IndentedFurther;
720 if (State.Stack.back().CallContinuation == 0)
721 State.Stack.back().CallContinuation = State.Column;
722 State.Column = State.Stack.back().CallContinuation;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000723 } else if (Current.Type == TT_ConditionalExpr) {
724 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000725 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000726 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
727 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000728 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000729 } else if (Previous.ClosesTemplateDeclaration ||
730 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000731 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000732 } else if (Current.Type == TT_ObjCSelectorName) {
733 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
734 State.Column =
735 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
736 } else {
737 State.Column = State.Stack.back().Indent;
738 State.Stack.back().ColonPos =
739 State.Column + Current.FormatTok.TokenLength;
740 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000741 } else if (Current.Type == TT_StartOfName || Current.is(tok::question) ||
742 Previous.is(tok::equal) || isComparison(Previous) ||
743 Previous.Type == TT_ObjCMethodExpr) {
744 // Indent and extra 4 spaces if the current expression is continued.
745 State.Column = IndentedFurther;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000746 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000747 State.Column = State.Stack.back().Indent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000748 if (State.Column == FirstIndent)
749 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000750 }
751
Daniel Jasper54a86022013-02-15 11:07:25 +0000752 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000753 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000754 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000755 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000756 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000757
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000758 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000759 unsigned NewLines = 1;
760 if (Current.Type == TT_LineComment)
761 NewLines =
762 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
763 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000764 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000765 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000766 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000767 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000768 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000769 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000770 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000771
Daniel Jasper400adc62013-02-08 15:28:42 +0000772 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000773 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000774
775 // Any break on this level means that the parent level has been broken
776 // and we need to avoid bin packing there.
777 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
778 State.Stack[i].BreakBeforeParameter = true;
779 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000780 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000781 State.Stack.back().BreakBeforeParameter = true;
782
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000783 // If we break after {, we should also break before the corresponding }.
784 if (Previous.is(tok::l_brace))
785 State.Stack.back().BreakBeforeClosingBrace = true;
786
787 if (State.Stack.back().AvoidBinPacking) {
788 // If we are breaking after '(', '{', '<', this is not bin packing
789 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000790 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000791 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
792 Line.MustBeDeclaration))
793 State.Stack.back().BreakBeforeParameter = true;
794 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000795 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000796 // FIXME: Put VariablePos into ParenState and remove second part of if().
797 if (Current.is(tok::equal) &&
798 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000799 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000800
Daniel Jaspereef30492013-02-11 12:36:37 +0000801 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000802
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000804 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000805
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000806 if (Current.Type == TT_ObjCSelectorName &&
807 State.Stack.back().ColonPos == 0) {
808 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000809 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000810 State.Stack.back().ColonPos =
811 State.Stack.back().Indent + Current.LongestObjCSelectorName;
812 else
813 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000814 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000815 }
816
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000817 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000818 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000819 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000820 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000821 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000822 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000823
Daniel Jaspere9de2602012-12-06 09:56:08 +0000824 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000825 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
826 // Treat the condition inside an if as if it was a second function
827 // parameter, i.e. let nested calls have an indent of 4.
828 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000829 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000830 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000831 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000832 Previous.Type == TT_ConditionalExpr ||
833 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000834 getPrecedence(Previous) != prec::Assignment)
835 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000836 else if (Previous.Type == TT_InheritanceColon)
837 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000838 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000839 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000840 Previous.Type == TT_TemplateOpener))
841 // If this function has multiple parameters, indent nested calls from
842 // the start of the first parameter.
843 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000844 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000845
Manuel Klimek1998ea22013-02-20 10:15:13 +0000846 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000847 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000848
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000849 /// \brief Mark the next token as consumed in \p State and modify its stacks
850 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000851 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000852 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000853 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000854
Daniel Jaspereead02b2013-02-14 08:42:54 +0000855 if (Current.Type == TT_InheritanceColon)
856 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000857 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
858 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000859 if (Current.is(tok::question))
860 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000861 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000862 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
863 State.Stack.back().StartOfFunctionCall =
864 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000865 if (Current.Type == TT_CtorInitializerColon) {
866 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
867 State.Stack.back().AvoidBinPacking = true;
868 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000869 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000870 if (Current.Type == TT_ObjCMethodSpecifier)
871 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000872
Daniel Jasper400adc62013-02-08 15:28:42 +0000873 // Insert scopes created by fake parenthesis.
874 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
875 ParenState NewParenState = State.Stack.back();
876 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000877 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000878 State.Stack.push_back(NewParenState);
879 }
880
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000881 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000882 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000883 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000884 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000885 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000886 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000887 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000888 NewIndent = 2 + State.Stack.back().LastSpace;
889 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000890 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000891 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
892 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000893 AvoidBinPacking =
894 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000895 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000896 State.Stack.push_back(
897 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
898 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000899 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000900 }
901
Daniel Jasperacc33662013-02-08 08:22:00 +0000902 // If this '[' opens an ObjC call, determine whether all parameters fit into
903 // one line and put one per line if they don't.
904 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
905 Current.MatchingParen != NULL) {
906 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
907 State.Stack.back().BreakBeforeParameter = true;
908 }
909
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000910 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000911 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000912 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000913 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
914 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000915 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000916 --State.ParenLevel;
917 }
918
919 // Remove scopes created by fake parenthesis.
920 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
921 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000922 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000923
Manuel Klimek0c915712013-02-20 15:32:58 +0000924 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000925 State.StartOfStringLiteral = State.Column;
926 } else if (Current.isNot(tok::comment)) {
927 State.StartOfStringLiteral = 0;
928 }
929
Manuel Klimek1998ea22013-02-20 10:15:13 +0000930 State.Column += Current.FormatTok.TokenLength;
931
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (State.NextToken->Children.empty())
933 State.NextToken = NULL;
934 else
935 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000936
Manuel Klimek1998ea22013-02-20 10:15:13 +0000937 return breakProtrudingToken(Current, State, DryRun);
938 }
939
940 /// \brief If the current token sticks out over the end of the line, break
941 /// it if possible.
942 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
943 bool DryRun) {
944 if (Current.isNot(tok::string_literal))
945 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000946 // Only break up default narrow strings.
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000947 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
948 if (!LiteralData || *LiteralData != '"')
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000949 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000950
951 unsigned Penalty = 0;
952 unsigned TailOffset = 0;
953 unsigned TailLength = Current.FormatTok.TokenLength;
954 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
955 unsigned OffsetFromStart = 0;
956 while (StartColumn + TailLength > getColumnLimit()) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000957 StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000958 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000959 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000960 StringRef::size_type SplitPoint = getSplitPoint(
961 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000962 if (SplitPoint == StringRef::npos)
963 break;
964 assert(SplitPoint != 0);
965 // +2, because 'Text' starts after the opening quotes, and does not
966 // include the closing quote we need to insert.
967 unsigned WhitespaceStartColumn =
968 StartColumn + OffsetFromStart + SplitPoint + 2;
969 State.Stack.back().LastSpace = StartColumn;
970 if (!DryRun) {
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000971 Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
972 0, "\"", "\"", Line.InPPDirective, StartColumn,
973 WhitespaceStartColumn);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000974 }
975 TailOffset += SplitPoint + 1;
976 TailLength -= SplitPoint + 1;
977 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000978 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000979 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
980 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000981 }
982 State.Column = StartColumn + TailLength;
983 return Penalty;
984 }
985
986 StringRef::size_type
987 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000988 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000989 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000990 return SpaceOffset;
991 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000992 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000993 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000994 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
995 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000996 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000997 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000998 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 }
1000
Manuel Klimek5085d9b2013-03-08 18:59:48 +00001001 StringRef::size_type
1002 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
1003 StringRef::size_type NextEscape = Text.find('\\');
1004 while (NextEscape != StringRef::npos && NextEscape < Offset) {
1005 StringRef::size_type SequenceLength =
1006 getEscapeSequenceLength(Text.substr(NextEscape));
1007 if (Offset < NextEscape + SequenceLength)
1008 return NextEscape;
1009 NextEscape = Text.find('\\', NextEscape + SequenceLength);
1010 }
1011 return Offset;
1012 }
1013
1014 unsigned getEscapeSequenceLength(StringRef Text) {
1015 assert(Text[0] == '\\');
1016 if (Text.size() < 2)
1017 return 1;
1018
1019 switch (Text[1]) {
1020 case 'u':
1021 return 6;
1022 case 'U':
1023 return 10;
1024 case 'x':
1025 return getHexLength(Text);
1026 default:
1027 if (Text[1] >= '0' && Text[1] <= '7')
1028 return getOctalLength(Text);
1029 return 2;
1030 }
1031 }
1032
1033 unsigned getHexLength(StringRef Text) {
1034 unsigned I = 2; // Point after '\x'.
1035 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
1036 (Text[I] >= 'a' && Text[I] <= 'f') ||
1037 (Text[I] >= 'A' && Text[I] <= 'F'))) {
1038 ++I;
1039 }
1040 return I;
1041 }
1042
1043 unsigned getOctalLength(StringRef Text) {
1044 unsigned I = 1;
1045 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
1046 ++I;
1047 }
1048 return I;
1049 }
1050
Daniel Jasper2df93312013-01-09 10:16:05 +00001051 unsigned getColumnLimit() {
Alexander Kornienkoffd6d042013-03-27 11:52:18 +00001052 return calculateColumnLimit(Style, Line.InPPDirective);
Daniel Jasper2df93312013-01-09 10:16:05 +00001053 }
1054
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001055 /// \brief An edge in the solution space from \c Previous->State to \c State,
1056 /// inserting a newline dependent on the \c NewLine.
1057 struct StateNode {
1058 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001059 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001060 LineState State;
1061 bool NewLine;
1062 StateNode *Previous;
1063 };
Daniel Jasper4b866272013-02-01 11:00:45 +00001064
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001065 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
1066 ///
1067 /// In case of equal penalties, we want to prefer states that were inserted
1068 /// first. During state generation we make sure that we insert states first
1069 /// that break the line as late as possible.
1070 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1071
1072 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
1073 /// \c State has the given \c OrderedPenalty.
1074 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1075
1076 /// \brief The BFS queue type.
1077 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
1078 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +00001079
1080 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +00001081 ///
Daniel Jasper4b866272013-02-01 11:00:45 +00001082 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1083 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1084 /// find the shortest path (the one with lowest penalty) from \p InitialState
1085 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001086 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001087 std::set<LineState> Seen;
1088
Daniel Jasper4b866272013-02-01 11:00:45 +00001089 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001090 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001091 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
1092 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
1093 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001094
1095 // While not empty, take first element and follow edges.
1096 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001097 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +00001098 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001099 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001100 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +00001101 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001102 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001103 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +00001104
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001105 if (!Seen.insert(Node->State).second)
1106 // State already examined with lower penalty.
1107 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +00001108
Manuel Klimekaf491072013-02-13 10:54:19 +00001109 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
1110 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +00001111 }
1112
1113 if (Queue.empty())
1114 // We were unable to find a solution, do nothing.
1115 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +00001116 return 0;
1117
Daniel Jasper4b866272013-02-01 11:00:45 +00001118 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001119 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001120 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +00001121
Daniel Jasper4b866272013-02-01 11:00:45 +00001122 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001123 return Queue.top().second->State.Column;
1124 }
1125
1126 void reconstructPath(LineState &State, StateNode *Current) {
1127 // FIXME: This recursive implementation limits the possible number
1128 // of tokens per line if compiled into a binary with small stack space.
1129 // To become more independent of stack frame limitations we would need
1130 // to also change the TokenAnnotator.
1131 if (Current->Previous == NULL)
1132 return;
1133 reconstructPath(State, Current->Previous);
1134 DEBUG({
1135 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +00001136 llvm::errs()
1137 << "Penalty for splitting before "
1138 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
1139 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001140 }
1141 });
1142 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +00001143 }
1144
Manuel Klimekaf491072013-02-13 10:54:19 +00001145 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +00001146 ///
Manuel Klimekaf491072013-02-13 10:54:19 +00001147 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +00001148 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +00001149 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1150 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001151 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001152 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001153 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +00001154 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001155 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001156 Penalty += PreviousNode->State.NextToken->SplitPenalty;
1157
1158 StateNode *Node = new (Allocator.Allocate())
1159 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +00001160 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001161 if (Node->State.Column > getColumnLimit()) {
1162 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +00001163 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +00001164 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +00001165
1166 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
1167 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +00001168 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001169
Daniel Jasper4b866272013-02-01 11:00:45 +00001170 /// \brief Returns \c true, if a line break after \p State is allowed.
1171 bool canBreak(const LineState &State) {
1172 if (!State.NextToken->CanBreakBefore &&
1173 !(State.NextToken->is(tok::r_brace) &&
1174 State.Stack.back().BreakBeforeClosingBrace))
1175 return false;
1176 // Trying to insert a parameter on a new line if there are already more than
1177 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +00001178 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +00001179 State.Stack.back().AvoidBinPacking)
1180 return false;
1181 return true;
1182 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001183
Daniel Jasper4b866272013-02-01 11:00:45 +00001184 /// \brief Returns \c true, if a line break after \p State is mandatory.
1185 bool mustBreak(const LineState &State) {
1186 if (State.NextToken->MustBreakBefore)
1187 return true;
1188 if (State.NextToken->is(tok::r_brace) &&
1189 State.Stack.back().BreakBeforeClosingBrace)
1190 return true;
1191 if (State.NextToken->Parent->is(tok::semi) &&
1192 State.LineContainsContinuedForLoopSection)
1193 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001194 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +00001195 State.NextToken->is(tok::question) ||
1196 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001197 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +00001198 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +00001199 State.NextToken->isNot(tok::r_paren) &&
1200 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +00001201 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +00001202 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
1203 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001204 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +00001205 State.NextToken->LongestObjCSelectorName == 0 &&
1206 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +00001207 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001208 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1209 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001210 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001211 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001212 if (State.NextToken->Type == TT_InlineASMColon)
1213 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +00001214 // This prevents breaks like:
1215 // ...
1216 // SomeParameter, OtherParameter).DoSomething(
1217 // ...
1218 // As they hide "DoSomething" and generally bad for readability.
1219 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
1220 getRemainingLength(State) + State.Column > getColumnLimit() &&
1221 State.ParenLevel < State.StartOfLineLevel)
1222 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001223 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001224 }
1225
Daniel Jasper9b334242013-03-15 14:57:30 +00001226 // Returns the total number of columns required for the remaining tokens.
1227 unsigned getRemainingLength(const LineState &State) {
1228 if (State.NextToken && State.NextToken->Parent)
1229 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
1230 return 0;
1231 }
1232
Daniel Jasperf7935112012-12-03 18:12:45 +00001233 FormatStyle Style;
1234 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001235 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001236 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001237 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001238 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001239
1240 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1241 QueueType Queue;
1242 // Increasing count of \c StateNode items we have created. This is used
1243 // to create a deterministic order independent of the container.
1244 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245};
1246
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001247class LexerBasedFormatTokenSource : public FormatTokenSource {
1248public:
1249 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001250 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001251 IdentTable(Lex.getLangOpts()) {
1252 Lex.SetKeepWhitespaceMode(true);
1253 }
1254
1255 virtual FormatToken getNextToken() {
1256 if (GreaterStashed) {
1257 FormatTok.NewlinesBefore = 0;
1258 FormatTok.WhiteSpaceStart =
1259 FormatTok.Tok.getLocation().getLocWithOffset(1);
1260 FormatTok.WhiteSpaceLength = 0;
1261 GreaterStashed = false;
1262 return FormatTok;
1263 }
1264
1265 FormatTok = FormatToken();
1266 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001267 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001268 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001269 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1270 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001271
1272 // Consume and record whitespace until we find a significant token.
1273 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001274 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001275 if (Newlines > 0)
1276 FormatTok.LastNewlineOffset =
1277 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001278 unsigned EscapedNewlines = Text.count("\\\n");
1279 FormatTok.NewlinesBefore += Newlines;
1280 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001281 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1282
1283 if (FormatTok.Tok.is(tok::eof))
1284 return FormatTok;
1285 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001286 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001287 }
Manuel Klimekef920692013-01-07 07:56:50 +00001288
1289 // Now FormatTok is the next non-whitespace token.
1290 FormatTok.TokenLength = Text.size();
1291
Manuel Klimek1abf7892013-01-04 23:34:14 +00001292 // In case the token starts with escaped newlines, we want to
1293 // take them into account as whitespace - this pattern is quite frequent
1294 // in macro definitions.
1295 // FIXME: What do we want to do with other escaped spaces, and escaped
1296 // spaces or newlines in the middle of tokens?
1297 // FIXME: Add a more explicit test.
1298 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001299 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001300 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001301 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001302 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001303 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001304 }
1305
1306 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001307 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001308 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001309 FormatTok.Tok.setKind(Info.getTokenID());
1310 }
1311
1312 if (FormatTok.Tok.is(tok::greatergreater)) {
1313 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001314 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001315 GreaterStashed = true;
1316 }
1317
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001318 // If we reformat comments, we remove trailing whitespace. Update the length
1319 // accordingly.
1320 if (FormatTok.Tok.is(tok::comment))
1321 FormatTok.TokenLength = Text.rtrim().size();
1322
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001323 return FormatTok;
1324 }
1325
Nico Weber29f9dea2013-02-11 15:32:15 +00001326 IdentifierTable &getIdentTable() { return IdentTable; }
1327
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001328private:
1329 FormatToken FormatTok;
1330 bool GreaterStashed;
1331 Lexer &Lex;
1332 SourceManager &SourceMgr;
1333 IdentifierTable IdentTable;
1334
1335 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001336 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001337 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1338 Tok.getLength());
1339 }
1340};
1341
Daniel Jasperf7935112012-12-03 18:12:45 +00001342class Formatter : public UnwrappedLineConsumer {
1343public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001344 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1345 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001346 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001347 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001348 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001349
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001350 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001351
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001352 tooling::Replacements format() {
1353 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1354 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1355 StructuralError = Parser.parse();
1356 unsigned PreviousEndOfLineColumn = 0;
1357 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1358 Tokens.getIdentTable().get("in"));
1359 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1360 Annotator.annotate(AnnotatedLines[i]);
1361 }
1362 deriveLocalStyle();
1363 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1364 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper0f8ed9e2013-03-13 15:53:12 +00001365
1366 // Adapt level to the next line if this is a comment.
1367 // FIXME: Can/should this be done in the UnwrappedLineParser?
1368 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1369 AnnotatedLines[i].First.Children.empty() &&
1370 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1371 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001372 }
1373 std::vector<int> IndentForLevel;
1374 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001375 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001376 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1377 E = AnnotatedLines.end();
1378 I != E; ++I) {
1379 const AnnotatedLine &TheLine = *I;
1380 const FormatToken &FirstTok = TheLine.First.FormatTok;
1381 int Offset = getIndentOffset(TheLine.First);
1382 while (IndentForLevel.size() <= TheLine.Level)
1383 IndentForLevel.push_back(-1);
1384 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001385 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001386 if (TheLine.First.is(tok::eof)) {
1387 if (PreviousLineWasTouched) {
1388 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1389 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001390 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001391 }
1392 } else if (TheLine.Type != LT_Invalid &&
1393 (WasMoved || touchesLine(TheLine))) {
1394 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1395 unsigned Indent = LevelIndent;
1396 if (static_cast<int>(Indent) + Offset >= 0)
1397 Indent += Offset;
1398 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001399 Indent = LevelIndent =
1400 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001401 } else {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001402 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1403 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001404 }
1405 tryFitMultipleLinesInOne(Indent, I, E);
1406 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1407 TheLine.First, Whitespaces,
1408 StructuralError);
1409 PreviousEndOfLineColumn =
1410 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1411 IndentForLevel[TheLine.Level] = LevelIndent;
1412 PreviousLineWasTouched = true;
1413 } else {
1414 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1415 unsigned Indent =
1416 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1417 unsigned LevelIndent = Indent;
1418 if (static_cast<int>(LevelIndent) - Offset >= 0)
1419 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001420 if (TheLine.First.isNot(tok::comment))
1421 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001422
1423 // Remove trailing whitespace of the previous line if it was touched.
1424 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001425 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1426 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001427 }
1428 // If we did not reformat this unwrapped line, the column at the end of
1429 // the last token is unchanged - thus, we can calculate the end of the
1430 // last token.
1431 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1432 PreviousEndOfLineColumn =
1433 SourceMgr.getSpellingColumnNumber(LastLoc) +
1434 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1435 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001436 if (TheLine.Last->is(tok::comment))
1437 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1438 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001439 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001440 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001441 }
1442 return Whitespaces.generateReplacements();
1443 }
1444
1445private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001446 void deriveLocalStyle() {
1447 unsigned CountBoundToVariable = 0;
1448 unsigned CountBoundToType = 0;
1449 bool HasCpp03IncompatibleFormat = false;
1450 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1451 if (AnnotatedLines[i].First.Children.empty())
1452 continue;
1453 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1454 while (!Tok->Children.empty()) {
1455 if (Tok->Type == TT_PointerOrReference) {
1456 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1457 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1458 if (SpacesBefore && !SpacesAfter)
1459 ++CountBoundToVariable;
1460 else if (!SpacesBefore && SpacesAfter)
1461 ++CountBoundToType;
1462 }
1463
Daniel Jasper400adc62013-02-08 15:28:42 +00001464 if (Tok->Type == TT_TemplateCloser &&
1465 Tok->Parent->Type == TT_TemplateCloser &&
1466 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001467 HasCpp03IncompatibleFormat = true;
1468 Tok = &Tok->Children[0];
1469 }
1470 }
1471 if (Style.DerivePointerBinding) {
1472 if (CountBoundToType > CountBoundToVariable)
1473 Style.PointerBindsToType = true;
1474 else if (CountBoundToType < CountBoundToVariable)
1475 Style.PointerBindsToType = false;
1476 }
1477 if (Style.Standard == FormatStyle::LS_Auto) {
1478 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1479 : FormatStyle::LS_Cpp03;
1480 }
1481 }
1482
Manuel Klimekb95f5452013-02-08 17:38:27 +00001483 /// \brief Get the indent of \p Level from \p IndentForLevel.
1484 ///
1485 /// \p IndentForLevel must contain the indent for the level \c l
1486 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1487 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001488 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001489 if (IndentForLevel[Level] != -1)
1490 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001491 if (Level == 0)
1492 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001493 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001494 }
1495
1496 /// \brief Get the offset of the line relatively to the level.
1497 ///
1498 /// For example, 'public:' labels in classes are offset by 1 or 2
1499 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001500 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001501 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001502 return Style.AccessModifierOffset;
1503 return 0;
1504 }
1505
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001506 /// \brief Tries to merge lines into one.
1507 ///
1508 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1509 /// if possible; note that \c I will be incremented when lines are merged.
1510 ///
1511 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001512 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001513 std::vector<AnnotatedLine>::iterator &I,
1514 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001515 // We can never merge stuff if there are trailing line comments.
1516 if (I->Last->Type == TT_LineComment)
1517 return;
1518
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001519 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001520 // If we already exceed the column limit, we set 'Limit' to 0. The different
1521 // tryMerge..() functions can then decide whether to still do merging.
1522 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001523
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001524 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001525 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001526
Daniel Jasper25837aa2013-01-14 14:14:23 +00001527 if (I->Last->is(tok::l_brace)) {
1528 tryMergeSimpleBlock(I, E, Limit);
1529 } else if (I->First.is(tok::kw_if)) {
1530 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001531 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1532 I->First.FormatTok.IsFirst)) {
1533 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001534 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001535 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001536 }
1537
Daniel Jasper39825ea2013-01-14 15:40:57 +00001538 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1539 std::vector<AnnotatedLine>::iterator E,
1540 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001541 if (Limit == 0)
1542 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001543 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001544 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1545 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001546 if (I + 2 != E && (I + 2)->InPPDirective &&
1547 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1548 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001549 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001550 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001551 join(Line, *(++I));
1552 }
1553
Daniel Jasper25837aa2013-01-14 14:14:23 +00001554 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1555 std::vector<AnnotatedLine>::iterator E,
1556 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001557 if (Limit == 0)
1558 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001559 if (!Style.AllowShortIfStatementsOnASingleLine)
1560 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001561 if ((I + 1)->InPPDirective != I->InPPDirective ||
1562 ((I + 1)->InPPDirective &&
1563 (I + 1)->First.FormatTok.HasUnescapedNewline))
1564 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001565 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001566 if (Line.Last->isNot(tok::r_paren))
1567 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001568 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001569 return;
1570 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1571 return;
1572 // Only inline simple if's (no nested if or else).
1573 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1574 return;
1575 join(Line, *(++I));
1576 }
1577
1578 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001579 std::vector<AnnotatedLine>::iterator E,
1580 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001581 // First, check that the current line allows merging. This is the case if
1582 // we're not in a control flow statement and the last token is an opening
1583 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001584 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001585 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1586 tok::kw_else, tok::kw_try, tok::kw_catch,
1587 tok::kw_for,
1588 // This gets rid of all ObjC @ keywords and methods.
1589 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001590 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001591
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001592 AnnotatedToken *Tok = &(I + 1)->First;
1593 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001594 !Tok->MustBreakBefore) {
1595 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001596 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001597 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001598 join(Line, *(I + 1));
1599 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001600 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001601 // Check that we still have three lines and they fit into the limit.
1602 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1603 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001604 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001605
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001606 // Second, check that the next line does not contain any braces - if it
1607 // does, readability declines when putting it into a single line.
1608 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1609 return;
1610 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001611 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001612 return;
1613 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1614 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001615
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001616 // Last, check that the third line contains a single closing brace.
1617 Tok = &(I + 2)->First;
1618 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1619 Tok->MustBreakBefore)
1620 return;
1621
1622 join(Line, *(I + 1));
1623 join(Line, *(I + 2));
1624 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001625 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001626 }
1627
1628 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1629 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001630 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1631 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001632 }
1633
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001634 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001635 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001636 A.Last->Children.push_back(B.First);
1637 while (!A.Last->Children.empty()) {
1638 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001639 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001640 A.Last = &A.Last->Children[0];
1641 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001642 }
1643
Daniel Jasper97b89482013-03-13 07:49:51 +00001644 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001645 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1646 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1647 Ranges[i].getBegin()) &&
1648 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1649 Range.getBegin()))
1650 return true;
1651 }
1652 return false;
1653 }
1654
1655 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001656 const FormatToken *First = &TheLine.First.FormatTok;
1657 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001658 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001659 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1660 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001661 return touchesRanges(LineRange);
1662 }
1663
1664 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1665 const FormatToken *First = &TheLine.First.FormatTok;
1666 CharSourceRange LineRange = CharSourceRange::getCharRange(
1667 First->WhiteSpaceStart,
1668 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1669 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001670 }
1671
1672 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001673 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001674 }
1675
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001676 /// \brief Add a new line and the required indent before the first Token
1677 /// of the \c UnwrappedLine if there was no structural parsing error.
1678 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001679 void formatFirstToken(const AnnotatedToken &RootToken,
1680 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001681 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001682 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001683
Daniel Jasperbbc84152013-01-29 11:27:30 +00001684 unsigned Newlines =
1685 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001686 if (Newlines == 0 && !Tok.IsFirst)
1687 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001688
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001689 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001690 // Insert extra new line before access specifiers.
1691 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1692 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1693 ++Newlines;
1694
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001695 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001696 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001697 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001698 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001699 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001700 }
1701
Alexander Kornienko116ba682013-01-14 11:34:14 +00001702 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001703 FormatStyle Style;
1704 Lexer &Lex;
1705 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001706 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001707 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001708 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001709 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001710};
1711
Daniel Jasperbbc84152013-01-29 11:27:30 +00001712tooling::Replacements
1713reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1714 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001715 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001716 OwningPtr<DiagnosticConsumer> DiagPrinter;
1717 if (DiagClient == 0) {
1718 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1719 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1720 DiagClient = DiagPrinter.get();
1721 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001722 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001723 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001724 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001725 Diagnostics.setSourceManager(&SourceMgr);
1726 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001727 return formatter.format();
1728}
1729
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001730LangOptions getFormattingLangOpts() {
1731 LangOptions LangOpts;
1732 LangOpts.CPlusPlus = 1;
1733 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001734 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001735 LangOpts.Bool = 1;
1736 LangOpts.ObjC1 = 1;
1737 LangOpts.ObjC2 = 1;
1738 return LangOpts;
1739}
1740
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001741} // namespace format
1742} // namespace clang