blob: ab895c7d1c725818c385fcd422a4898d23ded87e [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 Jaspercd8599e2013-02-23 21:01:55 +0000556
557 // Any break on this level means that the parent level has been broken
558 // and we need to avoid bin packing there.
559 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
560 State.Stack[i].BreakBeforeParameter = true;
561 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000562 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000563 State.Stack.back().BreakBeforeParameter = true;
564
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000565 // If we break after {, we should also break before the corresponding }.
566 if (Previous.is(tok::l_brace))
567 State.Stack.back().BreakBeforeClosingBrace = true;
568
569 if (State.Stack.back().AvoidBinPacking) {
570 // If we are breaking after '(', '{', '<', this is not bin packing
571 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000572 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000573 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
574 Line.MustBeDeclaration))
575 State.Stack.back().BreakBeforeParameter = true;
576 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000578 // FIXME: Put VariablePos into ParenState and remove second part of if().
579 if (Current.is(tok::equal) &&
580 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000581 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000582
Daniel Jaspereef30492013-02-11 12:36:37 +0000583 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000584
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000586 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000587
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000588 if (Current.Type == TT_ObjCSelectorName &&
589 State.Stack.back().ColonPos == 0) {
590 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
591 State.Column + Spaces + Current.FormatTok.TokenLength)
592 State.Stack.back().ColonPos =
593 State.Stack.back().Indent + Current.LongestObjCSelectorName;
594 else
595 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000596 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000597 }
598
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000599 if (Current.Type != TT_LineComment &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000600 (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000601 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000602 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000603 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000604 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000605
Daniel Jaspere9de2602012-12-06 09:56:08 +0000606 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000607 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
608 // Treat the condition inside an if as if it was a second function
609 // parameter, i.e. let nested calls have an indent of 4.
610 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000611 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000612 // Top-level spaces are exempt as that mostly leads to better results.
613 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000614 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000615 Previous.Type == TT_ConditionalExpr ||
616 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000617 getPrecedence(Previous) != prec::Assignment)
618 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000619 else if (Previous.Type == TT_InheritanceColon)
620 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000621 else if (Previous.ParameterCount > 1 &&
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000622 (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000623 Previous.Type == TT_TemplateOpener))
624 // If this function has multiple parameters, indent nested calls from
625 // the start of the first parameter.
626 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000627 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000628
Manuel Klimek1998ea22013-02-20 10:15:13 +0000629 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000630 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000631
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000632 /// \brief Mark the next token as consumed in \p State and modify its stacks
633 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000634 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000635 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000636 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000637
Daniel Jaspereead02b2013-02-14 08:42:54 +0000638 if (Current.Type == TT_InheritanceColon)
639 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000640 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
641 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000642 if (Current.is(tok::question))
643 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000644 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000645 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
646 State.Stack.back().StartOfFunctionCall =
647 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000648 if (Current.Type == TT_CtorInitializerColon) {
649 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
650 State.Stack.back().AvoidBinPacking = true;
651 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000652 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000653
Daniel Jasper400adc62013-02-08 15:28:42 +0000654 // Insert scopes created by fake parenthesis.
655 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
656 ParenState NewParenState = State.Stack.back();
657 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000658 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000659 State.Stack.push_back(NewParenState);
660 }
661
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000662 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000663 // prepare for the following tokens.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000664 if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000665 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000666 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000667 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000668 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000669 NewIndent = 2 + State.Stack.back().LastSpace;
670 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000671 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000672 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
673 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000674 AvoidBinPacking =
675 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000676 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000677 State.Stack.push_back(
678 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
679 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000680 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000681 }
682
Daniel Jasperacc33662013-02-08 08:22:00 +0000683 // If this '[' opens an ObjC call, determine whether all parameters fit into
684 // one line and put one per line if they don't.
685 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
686 Current.MatchingParen != NULL) {
687 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
688 State.Stack.back().BreakBeforeParameter = true;
689 }
690
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000691 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000692 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000693 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000694 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
695 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000696 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000697 --State.ParenLevel;
698 }
699
700 // Remove scopes created by fake parenthesis.
701 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
702 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000703 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000704
Manuel Klimek0c915712013-02-20 15:32:58 +0000705 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000706 State.StartOfStringLiteral = State.Column;
707 } else if (Current.isNot(tok::comment)) {
708 State.StartOfStringLiteral = 0;
709 }
710
Manuel Klimek1998ea22013-02-20 10:15:13 +0000711 State.Column += Current.FormatTok.TokenLength;
712
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000713 if (State.NextToken->Children.empty())
714 State.NextToken = NULL;
715 else
716 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000717
Manuel Klimek1998ea22013-02-20 10:15:13 +0000718 return breakProtrudingToken(Current, State, DryRun);
719 }
720
721 /// \brief If the current token sticks out over the end of the line, break
722 /// it if possible.
723 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
724 bool DryRun) {
725 if (Current.isNot(tok::string_literal))
726 return 0;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000727 // Only break up default narrow strings.
728 if (StringRef(Current.FormatTok.Tok.getLiteralData()).find('"') != 0)
729 return 0;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000730
731 unsigned Penalty = 0;
732 unsigned TailOffset = 0;
733 unsigned TailLength = Current.FormatTok.TokenLength;
734 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
735 unsigned OffsetFromStart = 0;
736 while (StartColumn + TailLength > getColumnLimit()) {
Daniel Jasper97b89482013-03-13 07:49:51 +0000737 StringRef Text = StringRef(
738 Current.FormatTok.Tok.getLiteralData() + TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000739 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000740 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000741 StringRef::size_type SplitPoint = getSplitPoint(
742 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000743 if (SplitPoint == StringRef::npos)
744 break;
745 assert(SplitPoint != 0);
746 // +2, because 'Text' starts after the opening quotes, and does not
747 // include the closing quote we need to insert.
748 unsigned WhitespaceStartColumn =
749 StartColumn + OffsetFromStart + SplitPoint + 2;
750 State.Stack.back().LastSpace = StartColumn;
751 if (!DryRun) {
752 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
753 Line.InPPDirective, StartColumn,
754 WhitespaceStartColumn, Style);
755 }
756 TailOffset += SplitPoint + 1;
757 TailLength -= SplitPoint + 1;
758 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000759 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000760 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
761 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000762 }
763 State.Column = StartColumn + TailLength;
764 return Penalty;
765 }
766
767 StringRef::size_type
768 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000769 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000770 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000771 return SpaceOffset;
772 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimekabf6e032013-03-04 20:03:38 +0000773 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000774 return SlashOffset;
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000775 StringRef::size_type Split = getStartOfCharacter(Text, Offset);
776 if (Split != StringRef::npos && Split > 1)
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000777 // Do not split at 0.
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000778 return Split - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000779 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 }
781
Manuel Klimek5085d9b2013-03-08 18:59:48 +0000782 StringRef::size_type
783 getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
784 StringRef::size_type NextEscape = Text.find('\\');
785 while (NextEscape != StringRef::npos && NextEscape < Offset) {
786 StringRef::size_type SequenceLength =
787 getEscapeSequenceLength(Text.substr(NextEscape));
788 if (Offset < NextEscape + SequenceLength)
789 return NextEscape;
790 NextEscape = Text.find('\\', NextEscape + SequenceLength);
791 }
792 return Offset;
793 }
794
795 unsigned getEscapeSequenceLength(StringRef Text) {
796 assert(Text[0] == '\\');
797 if (Text.size() < 2)
798 return 1;
799
800 switch (Text[1]) {
801 case 'u':
802 return 6;
803 case 'U':
804 return 10;
805 case 'x':
806 return getHexLength(Text);
807 default:
808 if (Text[1] >= '0' && Text[1] <= '7')
809 return getOctalLength(Text);
810 return 2;
811 }
812 }
813
814 unsigned getHexLength(StringRef Text) {
815 unsigned I = 2; // Point after '\x'.
816 while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
817 (Text[I] >= 'a' && Text[I] <= 'f') ||
818 (Text[I] >= 'A' && Text[I] <= 'F'))) {
819 ++I;
820 }
821 return I;
822 }
823
824 unsigned getOctalLength(StringRef Text) {
825 unsigned I = 1;
826 while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
827 ++I;
828 }
829 return I;
830 }
831
Daniel Jasper2df93312013-01-09 10:16:05 +0000832 unsigned getColumnLimit() {
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000833 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000834 }
835
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000836 /// \brief An edge in the solution space from \c Previous->State to \c State,
837 /// inserting a newline dependent on the \c NewLine.
838 struct StateNode {
839 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000840 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000841 LineState State;
842 bool NewLine;
843 StateNode *Previous;
844 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000845
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
847 ///
848 /// In case of equal penalties, we want to prefer states that were inserted
849 /// first. During state generation we make sure that we insert states first
850 /// that break the line as late as possible.
851 typedef std::pair<unsigned, unsigned> OrderedPenalty;
852
853 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
854 /// \c State has the given \c OrderedPenalty.
855 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
856
857 /// \brief The BFS queue type.
858 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
859 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000860
861 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000862 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000863 /// This implements a variant of Dijkstra's algorithm on the graph that spans
864 /// the solution space (\c LineStates are the nodes). The algorithm tries to
865 /// find the shortest path (the one with lowest penalty) from \p InitialState
866 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000867 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000868 std::set<LineState> Seen;
869
Daniel Jasper4b866272013-02-01 11:00:45 +0000870 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000871 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000872 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
873 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
874 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000875
876 // While not empty, take first element and follow edges.
877 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000878 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000879 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000880 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000881 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000882 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000883 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000884 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000885
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000886 if (!Seen.insert(Node->State).second)
887 // State already examined with lower penalty.
888 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000889
Manuel Klimekaf491072013-02-13 10:54:19 +0000890 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
891 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000892 }
893
894 if (Queue.empty())
895 // We were unable to find a solution, do nothing.
896 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000897 return 0;
898
Daniel Jasper4b866272013-02-01 11:00:45 +0000899 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000900 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000901 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000902
Daniel Jasper4b866272013-02-01 11:00:45 +0000903 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000904 return Queue.top().second->State.Column;
905 }
906
907 void reconstructPath(LineState &State, StateNode *Current) {
908 // FIXME: This recursive implementation limits the possible number
909 // of tokens per line if compiled into a binary with small stack space.
910 // To become more independent of stack frame limitations we would need
911 // to also change the TokenAnnotator.
912 if (Current->Previous == NULL)
913 return;
914 reconstructPath(State, Current->Previous);
915 DEBUG({
916 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000917 llvm::errs()
918 << "Penalty for splitting before "
919 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
920 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000921 }
922 });
923 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000924 }
925
Manuel Klimekaf491072013-02-13 10:54:19 +0000926 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000927 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000928 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000929 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000930 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
931 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000932 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000933 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000934 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000935 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000936 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000937 Penalty += PreviousNode->State.NextToken->SplitPenalty;
938
939 StateNode *Node = new (Allocator.Allocate())
940 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000941 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000942 if (Node->State.Column > getColumnLimit()) {
943 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000944 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000945 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000946
947 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
948 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000949 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000950
Daniel Jasper4b866272013-02-01 11:00:45 +0000951 /// \brief Returns \c true, if a line break after \p State is allowed.
952 bool canBreak(const LineState &State) {
953 if (!State.NextToken->CanBreakBefore &&
954 !(State.NextToken->is(tok::r_brace) &&
955 State.Stack.back().BreakBeforeClosingBrace))
956 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000957 // This prevents breaks like:
958 // ...
959 // SomeParameter, OtherParameter).DoSomething(
960 // ...
961 // As they hide "DoSomething" and generally bad for readability.
962 if (State.NextToken->Parent->is(tok::l_paren) &&
963 State.ParenLevel <= State.StartOfLineLevel)
964 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000965 // Trying to insert a parameter on a new line if there are already more than
966 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000967 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000968 State.Stack.back().AvoidBinPacking)
969 return false;
970 return true;
971 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000972
Daniel Jasper4b866272013-02-01 11:00:45 +0000973 /// \brief Returns \c true, if a line break after \p State is mandatory.
974 bool mustBreak(const LineState &State) {
975 if (State.NextToken->MustBreakBefore)
976 return true;
977 if (State.NextToken->is(tok::r_brace) &&
978 State.Stack.back().BreakBeforeClosingBrace)
979 return true;
980 if (State.NextToken->Parent->is(tok::semi) &&
981 State.LineContainsContinuedForLoopSection)
982 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000983 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000984 State.NextToken->is(tok::question) ||
985 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000986 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000987 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000988 State.NextToken->isNot(tok::r_paren) &&
989 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000990 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000991 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
992 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000993 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000994 State.NextToken->LongestObjCSelectorName == 0 &&
995 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000996 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000997 if ((State.NextToken->Type == TT_CtorInitializerColon ||
998 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000999 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +00001000 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +00001001 if (State.NextToken->Type == TT_InlineASMColon)
1002 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +00001003 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]);
Daniel Jasper0f8ed9e2013-03-13 15:53:12 +00001138
1139 // Adapt level to the next line if this is a comment.
1140 // FIXME: Can/should this be done in the UnwrappedLineParser?
1141 if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
1142 AnnotatedLines[i].First.Children.empty() &&
1143 AnnotatedLines[i + 1].First.isNot(tok::r_brace))
1144 AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001145 }
1146 std::vector<int> IndentForLevel;
1147 bool PreviousLineWasTouched = false;
1148 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1149 E = AnnotatedLines.end();
1150 I != E; ++I) {
1151 const AnnotatedLine &TheLine = *I;
1152 const FormatToken &FirstTok = TheLine.First.FormatTok;
1153 int Offset = getIndentOffset(TheLine.First);
1154 while (IndentForLevel.size() <= TheLine.Level)
1155 IndentForLevel.push_back(-1);
1156 IndentForLevel.resize(TheLine.Level + 1);
1157 bool WasMoved =
1158 PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
1159 if (TheLine.First.is(tok::eof)) {
1160 if (PreviousLineWasTouched) {
1161 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1162 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
1163 /*WhitespaceStartColumn*/ 0, Style);
1164 }
1165 } else if (TheLine.Type != LT_Invalid &&
1166 (WasMoved || touchesLine(TheLine))) {
1167 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1168 unsigned Indent = LevelIndent;
1169 if (static_cast<int>(Indent) + Offset >= 0)
1170 Indent += Offset;
1171 if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
1172 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1173 FirstTok.Tok.getLocation()) - 1;
1174 } else {
1175 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1176 PreviousEndOfLineColumn);
1177 }
1178 tryFitMultipleLinesInOne(Indent, I, E);
1179 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1180 TheLine.First, Whitespaces,
1181 StructuralError);
1182 PreviousEndOfLineColumn =
1183 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1184 IndentForLevel[TheLine.Level] = LevelIndent;
1185 PreviousLineWasTouched = true;
1186 } else {
1187 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1188 unsigned Indent =
1189 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1190 unsigned LevelIndent = Indent;
1191 if (static_cast<int>(LevelIndent) - Offset >= 0)
1192 LevelIndent -= Offset;
1193 IndentForLevel[TheLine.Level] = LevelIndent;
1194
1195 // Remove trailing whitespace of the previous line if it was touched.
1196 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
1197 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1198 PreviousEndOfLineColumn);
1199 }
1200 // If we did not reformat this unwrapped line, the column at the end of
1201 // the last token is unchanged - thus, we can calculate the end of the
1202 // last token.
1203 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1204 PreviousEndOfLineColumn =
1205 SourceMgr.getSpellingColumnNumber(LastLoc) +
1206 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1207 PreviousLineWasTouched = false;
1208 }
1209 }
1210 return Whitespaces.generateReplacements();
1211 }
1212
1213private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001214 void deriveLocalStyle() {
1215 unsigned CountBoundToVariable = 0;
1216 unsigned CountBoundToType = 0;
1217 bool HasCpp03IncompatibleFormat = false;
1218 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1219 if (AnnotatedLines[i].First.Children.empty())
1220 continue;
1221 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1222 while (!Tok->Children.empty()) {
1223 if (Tok->Type == TT_PointerOrReference) {
1224 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1225 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1226 if (SpacesBefore && !SpacesAfter)
1227 ++CountBoundToVariable;
1228 else if (!SpacesBefore && SpacesAfter)
1229 ++CountBoundToType;
1230 }
1231
Daniel Jasper400adc62013-02-08 15:28:42 +00001232 if (Tok->Type == TT_TemplateCloser &&
1233 Tok->Parent->Type == TT_TemplateCloser &&
1234 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001235 HasCpp03IncompatibleFormat = true;
1236 Tok = &Tok->Children[0];
1237 }
1238 }
1239 if (Style.DerivePointerBinding) {
1240 if (CountBoundToType > CountBoundToVariable)
1241 Style.PointerBindsToType = true;
1242 else if (CountBoundToType < CountBoundToVariable)
1243 Style.PointerBindsToType = false;
1244 }
1245 if (Style.Standard == FormatStyle::LS_Auto) {
1246 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1247 : FormatStyle::LS_Cpp03;
1248 }
1249 }
1250
Manuel Klimekb95f5452013-02-08 17:38:27 +00001251 /// \brief Get the indent of \p Level from \p IndentForLevel.
1252 ///
1253 /// \p IndentForLevel must contain the indent for the level \c l
1254 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1255 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001256 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001257 if (IndentForLevel[Level] != -1)
1258 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001259 if (Level == 0)
1260 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001261 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001262 }
1263
1264 /// \brief Get the offset of the line relatively to the level.
1265 ///
1266 /// For example, 'public:' labels in classes are offset by 1 or 2
1267 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001268 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001269 bool IsAccessModifier = false;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001270 if (RootToken.isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
Manuel Klimekb95f5452013-02-08 17:38:27 +00001271 IsAccessModifier = true;
1272 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1273 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1274 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1275 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1276 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1277 IsAccessModifier = true;
1278
1279 if (IsAccessModifier)
1280 return Style.AccessModifierOffset;
1281 return 0;
1282 }
1283
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001284 /// \brief Tries to merge lines into one.
1285 ///
1286 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1287 /// if possible; note that \c I will be incremented when lines are merged.
1288 ///
1289 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001290 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001291 std::vector<AnnotatedLine>::iterator &I,
1292 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001293 // We can never merge stuff if there are trailing line comments.
1294 if (I->Last->Type == TT_LineComment)
1295 return;
1296
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001297 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001298 // If we already exceed the column limit, we set 'Limit' to 0. The different
1299 // tryMerge..() functions can then decide whether to still do merging.
1300 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001301
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001302 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001303 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001304
Daniel Jasper25837aa2013-01-14 14:14:23 +00001305 if (I->Last->is(tok::l_brace)) {
1306 tryMergeSimpleBlock(I, E, Limit);
1307 } else if (I->First.is(tok::kw_if)) {
1308 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001309 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1310 I->First.FormatTok.IsFirst)) {
1311 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001312 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001313 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001314 }
1315
Daniel Jasper39825ea2013-01-14 15:40:57 +00001316 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1317 std::vector<AnnotatedLine>::iterator E,
1318 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001319 if (Limit == 0)
1320 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001321 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001322 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1323 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001324 if (I + 2 != E && (I + 2)->InPPDirective &&
1325 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1326 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001327 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001328 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001329 join(Line, *(++I));
1330 }
1331
Daniel Jasper25837aa2013-01-14 14:14:23 +00001332 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1333 std::vector<AnnotatedLine>::iterator E,
1334 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001335 if (Limit == 0)
1336 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001337 if (!Style.AllowShortIfStatementsOnASingleLine)
1338 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001339 if ((I + 1)->InPPDirective != I->InPPDirective ||
1340 ((I + 1)->InPPDirective &&
1341 (I + 1)->First.FormatTok.HasUnescapedNewline))
1342 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001343 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001344 if (Line.Last->isNot(tok::r_paren))
1345 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001346 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001347 return;
1348 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1349 return;
1350 // Only inline simple if's (no nested if or else).
1351 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1352 return;
1353 join(Line, *(++I));
1354 }
1355
1356 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001357 std::vector<AnnotatedLine>::iterator E,
1358 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001359 // First, check that the current line allows merging. This is the case if
1360 // we're not in a control flow statement and the last token is an opening
1361 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001362 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001363 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1364 tok::kw_else, tok::kw_try, tok::kw_catch,
1365 tok::kw_for,
1366 // This gets rid of all ObjC @ keywords and methods.
1367 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001368 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001369
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001370 AnnotatedToken *Tok = &(I + 1)->First;
1371 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001372 !Tok->MustBreakBefore) {
1373 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001374 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001375 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001376 join(Line, *(I + 1));
1377 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001378 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001379 // Check that we still have three lines and they fit into the limit.
1380 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1381 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001382 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001383
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001384 // Second, check that the next line does not contain any braces - if it
1385 // does, readability declines when putting it into a single line.
1386 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1387 return;
1388 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001389 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001390 return;
1391 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1392 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001393
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001394 // Last, check that the third line contains a single closing brace.
1395 Tok = &(I + 2)->First;
1396 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1397 Tok->MustBreakBefore)
1398 return;
1399
1400 join(Line, *(I + 1));
1401 join(Line, *(I + 2));
1402 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001403 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001404 }
1405
1406 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1407 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001408 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1409 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001410 }
1411
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001412 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001413 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001414 A.Last->Children.push_back(B.First);
1415 while (!A.Last->Children.empty()) {
1416 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001417 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001418 A.Last = &A.Last->Children[0];
1419 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001420 }
1421
Daniel Jasper97b89482013-03-13 07:49:51 +00001422 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001423 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1424 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1425 Ranges[i].getBegin()) &&
1426 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1427 Range.getBegin()))
1428 return true;
1429 }
1430 return false;
1431 }
1432
1433 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001434 const FormatToken *First = &TheLine.First.FormatTok;
1435 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001436 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001437 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1438 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001439 return touchesRanges(LineRange);
1440 }
1441
1442 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1443 const FormatToken *First = &TheLine.First.FormatTok;
1444 CharSourceRange LineRange = CharSourceRange::getCharRange(
1445 First->WhiteSpaceStart,
1446 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1447 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001448 }
1449
1450 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001451 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001452 }
1453
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001454 /// \brief Add a new line and the required indent before the first Token
1455 /// of the \c UnwrappedLine if there was no structural parsing error.
1456 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001457 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1458 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001459 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001460
Daniel Jasperbbc84152013-01-29 11:27:30 +00001461 unsigned Newlines =
1462 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001463 if (Newlines == 0 && !Tok.IsFirst)
1464 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001465
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001466 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001467 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001468 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001469 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1470 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001471 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001472 }
1473
Alexander Kornienko116ba682013-01-14 11:34:14 +00001474 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001475 FormatStyle Style;
1476 Lexer &Lex;
1477 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001478 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001479 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001480 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001481 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001482};
1483
Daniel Jasperbbc84152013-01-29 11:27:30 +00001484tooling::Replacements
1485reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1486 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001487 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001488 OwningPtr<DiagnosticConsumer> DiagPrinter;
1489 if (DiagClient == 0) {
1490 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1491 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1492 DiagClient = DiagPrinter.get();
1493 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001494 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001495 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001496 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001497 Diagnostics.setSourceManager(&SourceMgr);
1498 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001499 return formatter.format();
1500}
1501
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001502LangOptions getFormattingLangOpts() {
1503 LangOptions LangOpts;
1504 LangOpts.CPlusPlus = 1;
1505 LangOpts.CPlusPlus11 = 1;
1506 LangOpts.Bool = 1;
1507 LangOpts.ObjC1 = 1;
1508 LangOpts.ObjC2 = 1;
1509 return LangOpts;
1510}
1511
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001512} // namespace format
1513} // namespace clang