blob: 67ca928a1adc450213bd446699f0626f1c7181eb [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"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperf7935112012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000064 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper1b750ed2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000077 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper94f0e132013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperacc33662013-02-08 08:22:00 +000088// Returns the length of everything up to the first possible line break after
89// the ), ], } or > matching \c Tok.
90static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
91 if (Tok.MatchingParen == NULL)
92 return 0;
93 AnnotatedToken *End = Tok.MatchingParen;
94 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
95 End = &End->Children[0];
96 }
97 return End->TotalLength - Tok.TotalLength + 1;
98}
99
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000100/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000101///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000102/// This includes special handling for certain constructs, e.g. the alignment of
103/// trailing line comments.
104class WhitespaceManager {
105public:
106 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
107
108 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
109 /// each \c AnnotatedToken.
110 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
111 unsigned Spaces, unsigned WhitespaceStartColumn,
112 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000113 // 2+ newlines mean an empty line separating logic scopes.
114 if (NewLines >= 2)
115 alignComments();
116
117 // Align line comments if they are trailing or if they continue other
118 // trailing comments.
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000119 if (isTrailingComment(Tok)) {
120 // Remove the comment's trailing whitespace.
121 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
122 Replaces.insert(tooling::Replacement(
123 SourceMgr, Tok.FormatTok.Tok.getLocation().getLocWithOffset(
124 Tok.FormatTok.TokenLength),
125 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
126
127 // Align comment with other comments.
128 if (Tok.Parent != NULL || !Comments.empty()) {
129 if (Style.ColumnLimit >=
130 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
131 Comments.push_back(StoredComment());
132 Comments.back().Tok = Tok.FormatTok;
133 Comments.back().Spaces = Spaces;
134 Comments.back().NewLines = NewLines;
135 if (NewLines == 0)
136 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
137 else
138 Comments.back().MinColumn = Spaces;
139 Comments.back().MaxColumn =
140 Style.ColumnLimit - Tok.FormatTok.TokenLength;
141 return;
142 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000143 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000144 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000145
146 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000147 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000148 alignComments();
Manuel Klimek1998ea22013-02-20 10:15:13 +0000149 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000150 }
151
152 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
153 /// backslashes to escape newlines inside a preprocessor directive.
154 ///
155 /// This function and \c replaceWhitespace have the same behavior if
156 /// \c Newlines == 0.
157 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
158 unsigned Spaces, unsigned WhitespaceStartColumn,
159 const FormatStyle &Style) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000160 storeReplacement(
161 Tok.FormatTok,
162 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
163 }
164
165 /// \brief Inserts a line break into the middle of a token.
166 ///
167 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
168 /// break and \p Postfix before the rest of the token starts in the next line.
169 ///
170 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
171 /// used to generate the correct line break.
172 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
173 StringRef Postfix, bool InPPDirective, unsigned Spaces,
174 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
175 std::string NewLineText;
176 if (!InPPDirective)
177 NewLineText = getNewLineText(1, Spaces);
178 else
179 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
180 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
181 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
182 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
183 Replaces.insert(
184 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
185 }
186
187 /// \brief Returns all the \c Replacements created during formatting.
188 const tooling::Replacements &generateReplacements() {
189 alignComments();
190 return Replaces;
191 }
192
193private:
194 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
195 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
196 }
197
198 std::string
199 getNewLineText(unsigned NewLines, unsigned Spaces,
200 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000201 std::string NewLineText;
202 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000203 unsigned Offset =
204 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000205 for (unsigned i = 0; i < NewLines; ++i) {
206 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
207 NewLineText += "\\\n";
208 Offset = 0;
209 }
210 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000211 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212 }
213
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000214 /// \brief Structure to store a comment for later layout and alignment.
215 struct StoredComment {
216 FormatToken Tok;
217 unsigned MinColumn;
218 unsigned MaxColumn;
219 unsigned NewLines;
220 unsigned Spaces;
221 };
222 SmallVector<StoredComment, 16> Comments;
223 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
224
225 /// \brief Try to align all stashed comments.
226 void alignComments() {
227 unsigned MinColumn = 0;
228 unsigned MaxColumn = UINT_MAX;
229 comment_iterator Start = Comments.begin();
230 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
231 ++I) {
232 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
233 alignComments(Start, I, MinColumn);
234 MinColumn = I->MinColumn;
235 MaxColumn = I->MaxColumn;
236 Start = I;
237 } else {
238 MinColumn = std::max(MinColumn, I->MinColumn);
239 MaxColumn = std::min(MaxColumn, I->MaxColumn);
240 }
241 }
242 alignComments(Start, Comments.end(), MinColumn);
243 Comments.clear();
244 }
245
246 /// \brief Put all the comments between \p I and \p E into \p Column.
247 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
248 while (I != E) {
249 unsigned Spaces = I->Spaces + Column - I->MinColumn;
250 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper400adc62013-02-08 15:28:42 +0000251 std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000252 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000253 }
254 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000255
256 /// \brief Stores \p Text as the replacement for the whitespace in front of
257 /// \p Tok.
258 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000259 // Don't create a replacement, if it does not change anything.
260 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
261 Tok.WhiteSpaceLength) == Text)
262 return;
263
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000264 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
265 Tok.WhiteSpaceLength, Text));
266 }
267
268 SourceManager &SourceMgr;
269 tooling::Replacements Replaces;
270};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000271
Daniel Jasperf7935112012-12-03 18:12:45 +0000272class UnwrappedLineFormatter {
273public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000274 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000275 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000276 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000277 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000278 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000279 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000280 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000281
Manuel Klimek1abf7892013-01-04 23:34:14 +0000282 /// \brief Formats an \c UnwrappedLine.
283 ///
284 /// \returns The column after the last token in the last line of the
285 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000286 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000287 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000288 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000289 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000290 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000291 State.Stack.push_back(
292 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
293 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000294 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000295 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000296 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000297 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000298 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000299
Manuel Klimek24998102013-01-16 14:55:28 +0000300 DEBUG({
301 DebugTokenState(*State.NextToken);
302 });
303
Daniel Jaspere9de2602012-12-06 09:56:08 +0000304 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000305 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000306
Daniel Jasper4b866272013-02-01 11:00:45 +0000307 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000308 unsigned ColumnLimit = Style.ColumnLimit;
309 if (NextLine && NextLine->InPPDirective &&
310 !NextLine->First.FormatTok.HasUnescapedNewline)
311 ColumnLimit = getColumnLimit();
312 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000313 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000314 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000315 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000316 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000318
Daniel Jasperacc33662013-02-08 08:22:00 +0000319 // If the ObjC method declaration does not fit on a line, we should format
320 // it with one arg per line.
321 if (Line.Type == LT_ObjCMethodDecl)
322 State.Stack.back().BreakBeforeParameter = true;
323
Daniel Jasper4b866272013-02-01 11:00:45 +0000324 // Find best solution in solution space.
325 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000326 }
327
328private:
Manuel Klimek24998102013-01-16 14:55:28 +0000329 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
330 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000331 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
332 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000333 llvm::errs();
334 }
335
Daniel Jasper337816e2013-01-11 10:22:12 +0000336 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000337 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
338 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000339 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
340 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000341 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000342 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
343 StartOfFunctionCall(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000344
Daniel Jasperf7935112012-12-03 18:12:45 +0000345 /// \brief The position to which a specific parenthesis level needs to be
346 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000347 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000348
Daniel Jaspere9de2602012-12-06 09:56:08 +0000349 /// \brief The position of the last space on each level.
350 ///
351 /// Used e.g. to break like:
352 /// functionCall(Parameter, otherCall(
353 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000354 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000355
Daniel Jaspere9de2602012-12-06 09:56:08 +0000356 /// \brief The position the first "<<" operator encountered on each level.
357 ///
358 /// Used to align "<<" operators. 0 if no such operator has been encountered
359 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000360 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000361
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000362 /// \brief Whether a newline needs to be inserted before the block's closing
363 /// brace.
364 ///
365 /// We only want to insert a newline before the closing brace if there also
366 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000367 bool BreakBeforeClosingBrace;
368
Daniel Jasperca6623b2013-01-28 12:45:14 +0000369 /// \brief The column of a \c ? in a conditional expression;
370 unsigned QuestionColumn;
371
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000372 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
373 /// lines, in this context.
374 bool AvoidBinPacking;
375
376 /// \brief Break after the next comma (or all the commas in this context if
377 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000378 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000379
380 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000381 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000382
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000383 /// \brief The position of the colon in an ObjC method declaration/call.
384 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000385
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000386 /// \brief The start of the most recent function in a builder-type call.
387 unsigned StartOfFunctionCall;
388
Daniel Jasper337816e2013-01-11 10:22:12 +0000389 bool operator<(const ParenState &Other) const {
390 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000391 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000392 if (LastSpace != Other.LastSpace)
393 return LastSpace < Other.LastSpace;
394 if (FirstLessLess != Other.FirstLessLess)
395 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000396 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
397 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000398 if (QuestionColumn != Other.QuestionColumn)
399 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000400 if (AvoidBinPacking != Other.AvoidBinPacking)
401 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000402 if (BreakBeforeParameter != Other.BreakBeforeParameter)
403 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000404 if (HasMultiParameterLine != Other.HasMultiParameterLine)
405 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000406 if (ColonPos != Other.ColonPos)
407 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000408 if (StartOfFunctionCall != Other.StartOfFunctionCall)
409 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000410 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000411 }
412 };
413
414 /// \brief The current state when indenting a unwrapped line.
415 ///
416 /// As the indenting tries different combinations this is copied by value.
417 struct LineState {
418 /// \brief The number of used columns in the current line.
419 unsigned Column;
420
421 /// \brief The token that needs to be next formatted.
422 const AnnotatedToken *NextToken;
423
Daniel Jasperbbc84152013-01-29 11:27:30 +0000424 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000425 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000426 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000427 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000428
429 /// \brief \c true if this line contains a continued for-loop section.
430 bool LineContainsContinuedForLoopSection;
431
Daniel Jasper400adc62013-02-08 15:28:42 +0000432 /// \brief The level of nesting inside (), [], <> and {}.
433 unsigned ParenLevel;
434
Daniel Jasper40c36c52013-02-18 11:05:07 +0000435 /// \brief The \c ParenLevel at the start of this line.
436 unsigned StartOfLineLevel;
437
Manuel Klimek02f640a2013-02-20 15:25:48 +0000438 /// \brief The start column of the string literal, if we're in a string
439 /// literal sequence, 0 otherwise.
440 unsigned StartOfStringLiteral;
441
Daniel Jasper337816e2013-01-11 10:22:12 +0000442 /// \brief A stack keeping track of properties applying to parenthesis
443 /// levels.
444 std::vector<ParenState> Stack;
445
446 /// \brief Comparison operator to be able to used \c LineState in \c map.
447 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000448 if (NextToken != Other.NextToken)
449 return NextToken < Other.NextToken;
450 if (Column != Other.Column)
451 return Column < Other.Column;
452 if (VariablePos != Other.VariablePos)
453 return VariablePos < Other.VariablePos;
454 if (LineContainsContinuedForLoopSection !=
455 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000456 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000457 if (ParenLevel != Other.ParenLevel)
458 return ParenLevel < Other.ParenLevel;
459 if (StartOfLineLevel != Other.StartOfLineLevel)
460 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000461 if (StartOfStringLiteral != Other.StartOfStringLiteral)
462 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000463 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000464 }
465 };
466
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000467 /// \brief Appends the next token to \p State and updates information
468 /// necessary for indentation.
469 ///
470 /// Puts the token on the current line if \p Newline is \c true and adds a
471 /// line break and necessary indentation otherwise.
472 ///
473 /// If \p DryRun is \c false, also creates and stores the required
474 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000475 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000476 const AnnotatedToken &Current = *State.NextToken;
477 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000478 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000479
Daniel Jasper4b866272013-02-01 11:00:45 +0000480 if (Current.Type == TT_ImplicitStringLiteral) {
481 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
482 State.NextToken->FormatTok.TokenLength;
483 if (State.NextToken->Children.empty())
484 State.NextToken = NULL;
485 else
486 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000487 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000488 }
489
Daniel Jasperf7935112012-12-03 18:12:45 +0000490 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000491 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000492 if (Current.is(tok::r_brace)) {
493 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000494 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000495 State.StartOfStringLiteral != 0) {
496 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000497 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000498 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000499 State.Stack.back().FirstLessLess != 0) {
500 State.Column = State.Stack.back().FirstLessLess;
501 } else if (State.ParenLevel != 0 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000502 (Previous.isOneOf(tok::equal, tok::coloncolon) ||
503 Current.isOneOf(tok::period, tok::arrow, tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000504 // Indent and extra 4 spaces after if we know the current expression is
505 // continued. Don't do that on the top level, as we already indent 4
506 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000507 State.Column = std::max(State.Stack.back().LastSpace,
508 State.Stack.back().Indent) + 4;
509 } else if (Current.Type == TT_ConditionalExpr) {
510 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000511 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000512 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
513 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000514 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000515 } else if (Previous.ClosesTemplateDeclaration ||
516 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000517 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000518 } else if (Current.Type == TT_ObjCSelectorName) {
519 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
520 State.Column =
521 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
522 } else {
523 State.Column = State.Stack.back().Indent;
524 State.Stack.back().ColonPos =
525 State.Column + Current.FormatTok.TokenLength;
526 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000527 } else if (Previous.Type == TT_ObjCMethodExpr ||
528 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000529 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000530 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000531 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000532 }
533
Daniel Jasper54a86022013-02-15 11:07:25 +0000534 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000535 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000536 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000537 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000538 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000539
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000540 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000541 unsigned NewLines = 1;
542 if (Current.Type == TT_LineComment)
543 NewLines =
544 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
545 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000546 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000547 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000548 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000549 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000550 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000551 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000552 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000553
Daniel Jasper400adc62013-02-08 15:28:42 +0000554 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000555 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000556 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000557 State.Stack.back().Indent += 2;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000558
559 // Any break on this level means that the parent level has been broken
560 // and we need to avoid bin packing there.
561 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
562 State.Stack[i].BreakBeforeParameter = true;
563 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000564 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000565 State.Stack.back().BreakBeforeParameter = true;
566
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000567 // If we break after {, we should also break before the corresponding }.
568 if (Previous.is(tok::l_brace))
569 State.Stack.back().BreakBeforeClosingBrace = true;
570
571 if (State.Stack.back().AvoidBinPacking) {
572 // If we are breaking after '(', '{', '<', this is not bin packing
573 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000574 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000575 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
576 Line.MustBeDeclaration))
577 State.Stack.back().BreakBeforeParameter = true;
578 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000579 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000580 // FIXME: Put VariablePos into ParenState and remove second part of if().
581 if (Current.is(tok::equal) &&
582 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000583 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000584
Daniel Jaspereef30492013-02-11 12:36:37 +0000585 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000586
Daniel Jasperf7935112012-12-03 18:12:45 +0000587 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000588 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000590 if (Current.Type == TT_ObjCSelectorName &&
591 State.Stack.back().ColonPos == 0) {
592 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
593 State.Column + Spaces + Current.FormatTok.TokenLength)
594 State.Stack.back().ColonPos =
595 State.Stack.back().Indent + Current.LongestObjCSelectorName;
596 else
597 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000598 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000599 }
600
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000601 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000602 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000603 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000604 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000605 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000606 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000607
Daniel Jaspere9de2602012-12-06 09:56:08 +0000608 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000609 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
610 // Treat the condition inside an if as if it was a second function
611 // parameter, i.e. let nested calls have an indent of 4.
612 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000613 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000614 // Top-level spaces are exempt as that mostly leads to better results.
615 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000616 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000617 Previous.Type == TT_ConditionalExpr ||
618 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000619 getPrecedence(Previous) != prec::Assignment)
620 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000621 else if (Previous.Type == TT_InheritanceColon)
622 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000623 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000624 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000625 Previous.Type == TT_TemplateOpener))
626 // If this function has multiple parameters, indent nested calls from
627 // the start of the first parameter.
628 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000630
Manuel Klimek1998ea22013-02-20 10:15:13 +0000631 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000632 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000633
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000634 /// \brief Mark the next token as consumed in \p State and modify its stacks
635 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000636 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000637 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000638 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000639
Daniel Jaspereead02b2013-02-14 08:42:54 +0000640 if (Current.Type == TT_InheritanceColon)
641 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000642 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
643 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000644 if (Current.is(tok::question))
645 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000646 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000647 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
648 State.Stack.back().StartOfFunctionCall =
649 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000650 if (Current.Type == TT_CtorInitializerColon) {
651 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
652 State.Stack.back().AvoidBinPacking = true;
653 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000654 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000655
Daniel Jasper400adc62013-02-08 15:28:42 +0000656 // Insert scopes created by fake parenthesis.
657 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
658 ParenState NewParenState = State.Stack.back();
659 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000660 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000661 State.Stack.push_back(NewParenState);
662 }
663
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000664 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000665 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000666 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000667 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000668 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000669 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000670 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000671 NewIndent = 2 + State.Stack.back().LastSpace;
672 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000673 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000674 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
675 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000676 AvoidBinPacking =
677 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000678 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000679 State.Stack.push_back(
680 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
681 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000682 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000683 }
684
Daniel Jasperacc33662013-02-08 08:22:00 +0000685 // If this '[' opens an ObjC call, determine whether all parameters fit into
686 // one line and put one per line if they don't.
687 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
688 Current.MatchingParen != NULL) {
689 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
690 State.Stack.back().BreakBeforeParameter = true;
691 }
692
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000693 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000694 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000695 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
697 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000698 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000699 --State.ParenLevel;
700 }
701
702 // Remove scopes created by fake parenthesis.
703 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
704 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000705 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000706
Manuel Klimek0c915712013-02-20 15:32:58 +0000707 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000708 State.StartOfStringLiteral = State.Column;
709 } else if (Current.isNot(tok::comment)) {
710 State.StartOfStringLiteral = 0;
711 }
712
Manuel Klimek1998ea22013-02-20 10:15:13 +0000713 State.Column += Current.FormatTok.TokenLength;
714
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000715 if (State.NextToken->Children.empty())
716 State.NextToken = NULL;
717 else
718 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000719
Manuel Klimek1998ea22013-02-20 10:15:13 +0000720 return breakProtrudingToken(Current, State, DryRun);
721 }
722
723 /// \brief If the current token sticks out over the end of the line, break
724 /// it if possible.
725 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
726 bool DryRun) {
727 if (Current.isNot(tok::string_literal))
728 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000729 // Only break up default narrow strings.
730 if (StringRef(Current.FormatTok.Tok.getLiteralData()).find('"') != 0)
731 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000732
733 unsigned Penalty = 0;
734 unsigned TailOffset = 0;
735 unsigned TailLength = Current.FormatTok.TokenLength;
736 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
737 unsigned OffsetFromStart = 0;
738 while (StartColumn + TailLength > getColumnLimit()) {
Daniel Jasper97b89482013-03-13 07:49:51 +0000739 StringRef Text = StringRef(
740 Current.FormatTok.Tok.getLiteralData() + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000741 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000742 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000743 StringRef::size_type SplitPoint = getSplitPoint(
744 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000745 if (SplitPoint == StringRef::npos)
746 break;
747 assert(SplitPoint != 0);
748 // +2, because 'Text' starts after the opening quotes, and does not
749 // include the closing quote we need to insert.
750 unsigned WhitespaceStartColumn =
751 StartColumn + OffsetFromStart + SplitPoint + 2;
752 State.Stack.back().LastSpace = StartColumn;
753 if (!DryRun) {
754 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
755 Line.InPPDirective, StartColumn,
756 WhitespaceStartColumn, Style);
757 }
758 TailOffset += SplitPoint + 1;
759 TailLength -= SplitPoint + 1;
760 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000761 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000762 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
763 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000764 }
765 State.Column = StartColumn + TailLength;
766 return Penalty;
767 }
768
769 StringRef::size_type
770 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000771 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000772 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000773 return SpaceOffset;
774 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000775 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000776 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000777 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
778 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000779 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000780 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000781 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000782 }
783
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000784 StringRef::size_type
785 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
786 StringRef::size_type NextEscape = Text.find('\\');
787 while (NextEscape != StringRef::npos && NextEscape < Offset) {
788 StringRef::size_type SequenceLength =
789 getEscapeSequenceLength(Text.substr(NextEscape));
790 if (Offset < NextEscape + SequenceLength)
791 return NextEscape;
792 NextEscape = Text.find('\\', NextEscape + SequenceLength);
793 }
794 return Offset;
795 }
796
797 unsigned getEscapeSequenceLength(StringRef Text) {
798 assert(Text[0] == '\\');
799 if (Text.size() < 2)
800 return 1;
801
802 switch (Text[1]) {
803 case 'u':
804 return 6;
805 case 'U':
806 return 10;
807 case 'x':
808 return getHexLength(Text);
809 default:
810 if (Text[1] >= '0' && Text[1] <= '7')
811 return getOctalLength(Text);
812 return 2;
813 }
814 }
815
816 unsigned getHexLength(StringRef Text) {
817 unsigned I = 2; // Point after '\x'.
818 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
819 (Text[I] >= 'a' && Text[I] <= 'f') ||
820 (Text[I] >= 'A' && Text[I] <= 'F'))) {
821 ++I;
822 }
823 return I;
824 }
825
826 unsigned getOctalLength(StringRef Text) {
827 unsigned I = 1;
828 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
829 ++I;
830 }
831 return I;
832 }
833
Daniel Jasper2df93312013-01-09 10:16:05 +0000834 unsigned getColumnLimit() {
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000835 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000836 }
837
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000838 /// \brief An edge in the solution space from \c Previous->State to \c State,
839 /// inserting a newline dependent on the \c NewLine.
840 struct StateNode {
841 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000842 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000843 LineState State;
844 bool NewLine;
845 StateNode *Previous;
846 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000847
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000848 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
849 ///
850 /// In case of equal penalties, we want to prefer states that were inserted
851 /// first. During state generation we make sure that we insert states first
852 /// that break the line as late as possible.
853 typedef std::pair<unsigned, unsigned> OrderedPenalty;
854
855 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
856 /// \c State has the given \c OrderedPenalty.
857 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
858
859 /// \brief The BFS queue type.
860 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
861 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000862
863 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000864 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000865 /// This implements a variant of Dijkstra's algorithm on the graph that spans
866 /// the solution space (\c LineStates are the nodes). The algorithm tries to
867 /// find the shortest path (the one with lowest penalty) from \p InitialState
868 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000869 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000870 std::set<LineState> Seen;
871
Daniel Jasper4b866272013-02-01 11:00:45 +0000872 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000873 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000874 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
875 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
876 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000877
878 // While not empty, take first element and follow edges.
879 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000880 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000881 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000882 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000883 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000884 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000885 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000886 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000887
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000888 if (!Seen.insert(Node->State).second)
889 // State already examined with lower penalty.
890 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000891
Manuel Klimekaf491072013-02-13 10:54:19 +0000892 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
893 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000894 }
895
896 if (Queue.empty())
897 // We were unable to find a solution, do nothing.
898 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000899 return 0;
900
Daniel Jasper4b866272013-02-01 11:00:45 +0000901 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000902 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000903 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000904
Daniel Jasper4b866272013-02-01 11:00:45 +0000905 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000906 return Queue.top().second->State.Column;
907 }
908
909 void reconstructPath(LineState &State, StateNode *Current) {
910 // FIXME: This recursive implementation limits the possible number
911 // of tokens per line if compiled into a binary with small stack space.
912 // To become more independent of stack frame limitations we would need
913 // to also change the TokenAnnotator.
914 if (Current->Previous == NULL)
915 return;
916 reconstructPath(State, Current->Previous);
917 DEBUG({
918 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000919 llvm::errs()
920 << "Penalty for splitting before "
921 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
922 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000923 }
924 });
925 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000926 }
927
Manuel Klimekaf491072013-02-13 10:54:19 +0000928 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000929 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000930 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000931 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000932 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
933 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000934 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000935 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000936 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000937 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000938 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000939 Penalty += PreviousNode->State.NextToken->SplitPenalty;
940
941 StateNode *Node = new (Allocator.Allocate())
942 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000943 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000944 if (Node->State.Column > getColumnLimit()) {
945 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000946 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000947 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000948
949 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
950 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000951 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000952
Daniel Jasper4b866272013-02-01 11:00:45 +0000953 /// \brief Returns \c true, if a line break after \p State is allowed.
954 bool canBreak(const LineState &State) {
955 if (!State.NextToken->CanBreakBefore &&
956 !(State.NextToken->is(tok::r_brace) &&
957 State.Stack.back().BreakBeforeClosingBrace))
958 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000959 // This prevents breaks like:
960 // ...
961 // SomeParameter, OtherParameter).DoSomething(
962 // ...
963 // As they hide "DoSomething" and generally bad for readability.
964 if (State.NextToken->Parent->is(tok::l_paren) &&
965 State.ParenLevel <= State.StartOfLineLevel)
966 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000967 // Trying to insert a parameter on a new line if there are already more than
968 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000969 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000970 State.Stack.back().AvoidBinPacking)
971 return false;
972 return true;
973 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000974
Daniel Jasper4b866272013-02-01 11:00:45 +0000975 /// \brief Returns \c true, if a line break after \p State is mandatory.
976 bool mustBreak(const LineState &State) {
977 if (State.NextToken->MustBreakBefore)
978 return true;
979 if (State.NextToken->is(tok::r_brace) &&
980 State.Stack.back().BreakBeforeClosingBrace)
981 return true;
982 if (State.NextToken->Parent->is(tok::semi) &&
983 State.LineContainsContinuedForLoopSection)
984 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000985 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000986 State.NextToken->is(tok::question) ||
987 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000988 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000989 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000990 State.NextToken->isNot(tok::r_paren) &&
991 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000992 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000993 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
994 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000995 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000996 State.NextToken->LongestObjCSelectorName == 0 &&
997 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000998 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000999 if ((State.NextToken->Type == TT_CtorInitializerColon ||
1000 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +00001001 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001002 return true;
1003 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001004 }
1005
Daniel Jasperf7935112012-12-03 18:12:45 +00001006 FormatStyle Style;
1007 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001008 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001009 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001011 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +00001012
1013 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1014 QueueType Queue;
1015 // Increasing count of \c StateNode items we have created. This is used
1016 // to create a deterministic order independent of the container.
1017 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +00001018};
1019
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001020class LexerBasedFormatTokenSource : public FormatTokenSource {
1021public:
1022 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001023 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001024 IdentTable(Lex.getLangOpts()) {
1025 Lex.SetKeepWhitespaceMode(true);
1026 }
1027
1028 virtual FormatToken getNextToken() {
1029 if (GreaterStashed) {
1030 FormatTok.NewlinesBefore = 0;
1031 FormatTok.WhiteSpaceStart =
1032 FormatTok.Tok.getLocation().getLocWithOffset(1);
1033 FormatTok.WhiteSpaceLength = 0;
1034 GreaterStashed = false;
1035 return FormatTok;
1036 }
1037
1038 FormatTok = FormatToken();
1039 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001040 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001041 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001042 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1043 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001044
1045 // Consume and record whitespace until we find a significant token.
1046 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +00001047 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +00001048 if (Newlines > 0)
1049 FormatTok.LastNewlineOffset =
1050 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +00001051 unsigned EscapedNewlines = Text.count("\\\n");
1052 FormatTok.NewlinesBefore += Newlines;
1053 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001054 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1055
1056 if (FormatTok.Tok.is(tok::eof))
1057 return FormatTok;
1058 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001059 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001060 }
Manuel Klimekef920692013-01-07 07:56:50 +00001061
1062 // Now FormatTok is the next non-whitespace token.
1063 FormatTok.TokenLength = Text.size();
1064
Manuel Klimek1abf7892013-01-04 23:34:14 +00001065 // In case the token starts with escaped newlines, we want to
1066 // take them into account as whitespace - this pattern is quite frequent
1067 // in macro definitions.
1068 // FIXME: What do we want to do with other escaped spaces, and escaped
1069 // spaces or newlines in the middle of tokens?
1070 // FIXME: Add a more explicit test.
1071 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001072 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001073 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001074 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001075 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001076 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001077 }
1078
1079 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001080 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001081 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001082 FormatTok.Tok.setKind(Info.getTokenID());
1083 }
1084
1085 if (FormatTok.Tok.is(tok::greatergreater)) {
1086 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001087 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001088 GreaterStashed = true;
1089 }
1090
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001091 // If we reformat comments, we remove trailing whitespace. Update the length
1092 // accordingly.
1093 if (FormatTok.Tok.is(tok::comment))
1094 FormatTok.TokenLength = Text.rtrim().size();
1095
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001096 return FormatTok;
1097 }
1098
Nico Weber29f9dea2013-02-11 15:32:15 +00001099 IdentifierTable &getIdentTable() { return IdentTable; }
1100
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001101private:
1102 FormatToken FormatTok;
1103 bool GreaterStashed;
1104 Lexer &Lex;
1105 SourceManager &SourceMgr;
1106 IdentifierTable IdentTable;
1107
1108 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001109 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001110 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1111 Tok.getLength());
1112 }
1113};
1114
Daniel Jasperf7935112012-12-03 18:12:45 +00001115class Formatter : public UnwrappedLineConsumer {
1116public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001117 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1118 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001119 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001120 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001121 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001122
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001123 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001124
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001125 tooling::Replacements format() {
1126 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1127 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
1128 StructuralError = Parser.parse();
1129 unsigned PreviousEndOfLineColumn = 0;
1130 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1131 Tokens.getIdentTable().get("in"));
1132 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1133 Annotator.annotate(AnnotatedLines[i]);
1134 }
1135 deriveLocalStyle();
1136 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1137 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1138 }
1139 std::vector<int> IndentForLevel;
1140 bool PreviousLineWasTouched = false;
1141 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1142 E = AnnotatedLines.end();
1143 I != E; ++I) {
1144 const AnnotatedLine &TheLine = *I;
1145 const FormatToken &FirstTok = TheLine.First.FormatTok;
1146 int Offset = getIndentOffset(TheLine.First);
1147 while (IndentForLevel.size() <= TheLine.Level)
1148 IndentForLevel.push_back(-1);
1149 IndentForLevel.resize(TheLine.Level + 1);
1150 bool WasMoved =
1151 PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
1152 if (TheLine.First.is(tok::eof)) {
1153 if (PreviousLineWasTouched) {
1154 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1155 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
1156 /*WhitespaceStartColumn*/ 0, Style);
1157 }
1158 } else if (TheLine.Type != LT_Invalid &&
1159 (WasMoved || touchesLine(TheLine))) {
1160 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1161 unsigned Indent = LevelIndent;
1162 if (static_cast<int>(Indent) + Offset >= 0)
1163 Indent += Offset;
1164 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
1165 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1166 FirstTok.Tok.getLocation()) - 1;
1167 } else {
1168 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1169 PreviousEndOfLineColumn);
1170 }
1171 tryFitMultipleLinesInOne(Indent, I, E);
1172 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1173 TheLine.First, Whitespaces,
1174 StructuralError);
1175 PreviousEndOfLineColumn =
1176 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1177 IndentForLevel[TheLine.Level] = LevelIndent;
1178 PreviousLineWasTouched = true;
1179 } else {
1180 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1181 unsigned Indent =
1182 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1183 unsigned LevelIndent = Indent;
1184 if (static_cast<int>(LevelIndent) - Offset >= 0)
1185 LevelIndent -= Offset;
1186 IndentForLevel[TheLine.Level] = LevelIndent;
1187
1188 // Remove trailing whitespace of the previous line if it was touched.
1189 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1190 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1191 PreviousEndOfLineColumn);
1192 }
1193 // If we did not reformat this unwrapped line, the column at the end of
1194 // the last token is unchanged - thus, we can calculate the end of the
1195 // last token.
1196 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1197 PreviousEndOfLineColumn =
1198 SourceMgr.getSpellingColumnNumber(LastLoc) +
1199 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1200 PreviousLineWasTouched = false;
1201 }
1202 }
1203 return Whitespaces.generateReplacements();
1204 }
1205
1206private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001207 void deriveLocalStyle() {
1208 unsigned CountBoundToVariable = 0;
1209 unsigned CountBoundToType = 0;
1210 bool HasCpp03IncompatibleFormat = false;
1211 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1212 if (AnnotatedLines[i].First.Children.empty())
1213 continue;
1214 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1215 while (!Tok->Children.empty()) {
1216 if (Tok->Type == TT_PointerOrReference) {
1217 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1218 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1219 if (SpacesBefore && !SpacesAfter)
1220 ++CountBoundToVariable;
1221 else if (!SpacesBefore && SpacesAfter)
1222 ++CountBoundToType;
1223 }
1224
Daniel Jasper400adc62013-02-08 15:28:42 +00001225 if (Tok->Type == TT_TemplateCloser &&
1226 Tok->Parent->Type == TT_TemplateCloser &&
1227 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001228 HasCpp03IncompatibleFormat = true;
1229 Tok = &Tok->Children[0];
1230 }
1231 }
1232 if (Style.DerivePointerBinding) {
1233 if (CountBoundToType > CountBoundToVariable)
1234 Style.PointerBindsToType = true;
1235 else if (CountBoundToType < CountBoundToVariable)
1236 Style.PointerBindsToType = false;
1237 }
1238 if (Style.Standard == FormatStyle::LS_Auto) {
1239 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1240 : FormatStyle::LS_Cpp03;
1241 }
1242 }
1243
Manuel Klimekb95f5452013-02-08 17:38:27 +00001244 /// \brief Get the indent of \p Level from \p IndentForLevel.
1245 ///
1246 /// \p IndentForLevel must contain the indent for the level \c l
1247 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1248 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001249 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001250 if (IndentForLevel[Level] != -1)
1251 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001252 if (Level == 0)
1253 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001254 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001255 }
1256
1257 /// \brief Get the offset of the line relatively to the level.
1258 ///
1259 /// For example, 'public:' labels in classes are offset by 1 or 2
1260 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001261 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001262 bool IsAccessModifier = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001263 if (RootToken.isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
Manuel Klimekb95f5452013-02-08 17:38:27 +00001264 IsAccessModifier = true;
1265 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1266 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1267 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1268 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1269 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1270 IsAccessModifier = true;
1271
1272 if (IsAccessModifier)
1273 return Style.AccessModifierOffset;
1274 return 0;
1275 }
1276
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001277 /// \brief Tries to merge lines into one.
1278 ///
1279 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1280 /// if possible; note that \c I will be incremented when lines are merged.
1281 ///
1282 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001283 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001284 std::vector<AnnotatedLine>::iterator &I,
1285 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001286 // We can never merge stuff if there are trailing line comments.
1287 if (I->Last->Type == TT_LineComment)
1288 return;
1289
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001290 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001291 // If we already exceed the column limit, we set 'Limit' to 0. The different
1292 // tryMerge..() functions can then decide whether to still do merging.
1293 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001294
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001295 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001296 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001297
Daniel Jasper25837aa2013-01-14 14:14:23 +00001298 if (I->Last->is(tok::l_brace)) {
1299 tryMergeSimpleBlock(I, E, Limit);
1300 } else if (I->First.is(tok::kw_if)) {
1301 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001302 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1303 I->First.FormatTok.IsFirst)) {
1304 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001305 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001306 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001307 }
1308
Daniel Jasper39825ea2013-01-14 15:40:57 +00001309 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1310 std::vector<AnnotatedLine>::iterator E,
1311 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001312 if (Limit == 0)
1313 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001314 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001315 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1316 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001317 if (I + 2 != E && (I + 2)->InPPDirective &&
1318 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1319 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001320 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001321 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001322 join(Line, *(++I));
1323 }
1324
Daniel Jasper25837aa2013-01-14 14:14:23 +00001325 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1326 std::vector<AnnotatedLine>::iterator E,
1327 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001328 if (Limit == 0)
1329 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001330 if (!Style.AllowShortIfStatementsOnASingleLine)
1331 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001332 if ((I + 1)->InPPDirective != I->InPPDirective ||
1333 ((I + 1)->InPPDirective &&
1334 (I + 1)->First.FormatTok.HasUnescapedNewline))
1335 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001336 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001337 if (Line.Last->isNot(tok::r_paren))
1338 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001339 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001340 return;
1341 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1342 return;
1343 // Only inline simple if's (no nested if or else).
1344 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1345 return;
1346 join(Line, *(++I));
1347 }
1348
1349 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001350 std::vector<AnnotatedLine>::iterator E,
1351 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001352 // First, check that the current line allows merging. This is the case if
1353 // we're not in a control flow statement and the last token is an opening
1354 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001355 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001356 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1357 tok::kw_else, tok::kw_try, tok::kw_catch,
1358 tok::kw_for,
1359 // This gets rid of all ObjC @ keywords and methods.
1360 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001361 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001362
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001363 AnnotatedToken *Tok = &(I + 1)->First;
1364 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001365 !Tok->MustBreakBefore) {
1366 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001367 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001368 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001369 join(Line, *(I + 1));
1370 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001371 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001372 // Check that we still have three lines and they fit into the limit.
1373 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1374 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001375 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001376
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001377 // Second, check that the next line does not contain any braces - if it
1378 // does, readability declines when putting it into a single line.
1379 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1380 return;
1381 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001382 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001383 return;
1384 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1385 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001386
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001387 // Last, check that the third line contains a single closing brace.
1388 Tok = &(I + 2)->First;
1389 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1390 Tok->MustBreakBefore)
1391 return;
1392
1393 join(Line, *(I + 1));
1394 join(Line, *(I + 2));
1395 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001396 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001397 }
1398
1399 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1400 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001401 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1402 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001403 }
1404
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001405 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001406 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001407 A.Last->Children.push_back(B.First);
1408 while (!A.Last->Children.empty()) {
1409 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001410 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001411 A.Last = &A.Last->Children[0];
1412 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001413 }
1414
Daniel Jasper97b89482013-03-13 07:49:51 +00001415 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001416 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1417 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1418 Ranges[i].getBegin()) &&
1419 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1420 Range.getBegin()))
1421 return true;
1422 }
1423 return false;
1424 }
1425
1426 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001427 const FormatToken *First = &TheLine.First.FormatTok;
1428 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001429 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001430 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1431 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001432 return touchesRanges(LineRange);
1433 }
1434
1435 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1436 const FormatToken *First = &TheLine.First.FormatTok;
1437 CharSourceRange LineRange = CharSourceRange::getCharRange(
1438 First->WhiteSpaceStart,
1439 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1440 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001441 }
1442
1443 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001444 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001445 }
1446
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001447 /// \brief Add a new line and the required indent before the first Token
1448 /// of the \c UnwrappedLine if there was no structural parsing error.
1449 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001450 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1451 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001452 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001453
Daniel Jasperbbc84152013-01-29 11:27:30 +00001454 unsigned Newlines =
1455 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001456 if (Newlines == 0 && !Tok.IsFirst)
1457 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001458
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001459 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001460 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001461 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001462 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1463 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001464 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001465 }
1466
Alexander Kornienko116ba682013-01-14 11:34:14 +00001467 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001468 FormatStyle Style;
1469 Lexer &Lex;
1470 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001471 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001472 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001473 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001474 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001475};
1476
Daniel Jasperbbc84152013-01-29 11:27:30 +00001477tooling::Replacements
1478reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1479 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001480 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001481 OwningPtr<DiagnosticConsumer> DiagPrinter;
1482 if (DiagClient == 0) {
1483 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1484 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1485 DiagClient = DiagPrinter.get();
1486 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001487 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001488 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001489 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001490 Diagnostics.setSourceManager(&SourceMgr);
1491 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001492 return formatter.format();
1493}
1494
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001495LangOptions getFormattingLangOpts() {
1496 LangOptions LangOpts;
1497 LangOpts.CPlusPlus = 1;
1498 LangOpts.CPlusPlus11 = 1;
1499 LangOpts.Bool = 1;
1500 LangOpts.ObjC1 = 1;
1501 LangOpts.ObjC2 = 1;
1502 return LangOpts;
1503}
1504
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001505} // namespace format
1506} // namespace clang