blob: 5fd49157bd4c3f2fdcbb0daef2a5abb787cba097 [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 Jasperdc7d5812013-02-20 12:56:39 +0000291 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
292 !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 Jaspercd8599e2013-02-23 21:01:55 +0000342 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000343
Daniel Jasperf7935112012-12-03 18:12:45 +0000344 /// \brief The position to which a specific parenthesis level needs to be
345 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000346 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000347
Daniel Jaspere9de2602012-12-06 09:56:08 +0000348 /// \brief The position of the last space on each level.
349 ///
350 /// Used e.g. to break like:
351 /// functionCall(Parameter, otherCall(
352 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000353 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000354
Daniel Jaspere9de2602012-12-06 09:56:08 +0000355 /// \brief The position the first "<<" operator encountered on each level.
356 ///
357 /// Used to align "<<" operators. 0 if no such operator has been encountered
358 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000359 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000360
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000361 /// \brief Whether a newline needs to be inserted before the block's closing
362 /// brace.
363 ///
364 /// We only want to insert a newline before the closing brace if there also
365 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000366 bool BreakBeforeClosingBrace;
367
Daniel Jasperca6623b2013-01-28 12:45:14 +0000368 /// \brief The column of a \c ? in a conditional expression;
369 unsigned QuestionColumn;
370
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000371 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
372 /// lines, in this context.
373 bool AvoidBinPacking;
374
375 /// \brief Break after the next comma (or all the commas in this context if
376 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000377 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000378
379 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000380 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000381
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000382 /// \brief The position of the colon in an ObjC method declaration/call.
383 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000384
Daniel Jasper337816e2013-01-11 10:22:12 +0000385 bool operator<(const ParenState &Other) const {
386 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000387 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000388 if (LastSpace != Other.LastSpace)
389 return LastSpace < Other.LastSpace;
390 if (FirstLessLess != Other.FirstLessLess)
391 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000392 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
393 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000394 if (QuestionColumn != Other.QuestionColumn)
395 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000396 if (AvoidBinPacking != Other.AvoidBinPacking)
397 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000398 if (BreakBeforeParameter != Other.BreakBeforeParameter)
399 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000400 if (HasMultiParameterLine != Other.HasMultiParameterLine)
401 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000402 if (ColonPos != Other.ColonPos)
403 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000404 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000405 }
406 };
407
408 /// \brief The current state when indenting a unwrapped line.
409 ///
410 /// As the indenting tries different combinations this is copied by value.
411 struct LineState {
412 /// \brief The number of used columns in the current line.
413 unsigned Column;
414
415 /// \brief The token that needs to be next formatted.
416 const AnnotatedToken *NextToken;
417
Daniel Jasperbbc84152013-01-29 11:27:30 +0000418 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000419 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000420 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000421 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000422
423 /// \brief \c true if this line contains a continued for-loop section.
424 bool LineContainsContinuedForLoopSection;
425
Daniel Jasper400adc62013-02-08 15:28:42 +0000426 /// \brief The level of nesting inside (), [], <> and {}.
427 unsigned ParenLevel;
428
Daniel Jasper40c36c52013-02-18 11:05:07 +0000429 /// \brief The \c ParenLevel at the start of this line.
430 unsigned StartOfLineLevel;
431
Manuel Klimek02f640a2013-02-20 15:25:48 +0000432 /// \brief The start column of the string literal, if we're in a string
433 /// literal sequence, 0 otherwise.
434 unsigned StartOfStringLiteral;
435
Daniel Jasper337816e2013-01-11 10:22:12 +0000436 /// \brief A stack keeping track of properties applying to parenthesis
437 /// levels.
438 std::vector<ParenState> Stack;
439
440 /// \brief Comparison operator to be able to used \c LineState in \c map.
441 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000442 if (NextToken != Other.NextToken)
443 return NextToken < Other.NextToken;
444 if (Column != Other.Column)
445 return Column < Other.Column;
446 if (VariablePos != Other.VariablePos)
447 return VariablePos < Other.VariablePos;
448 if (LineContainsContinuedForLoopSection !=
449 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000450 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000451 if (ParenLevel != Other.ParenLevel)
452 return ParenLevel < Other.ParenLevel;
453 if (StartOfLineLevel != Other.StartOfLineLevel)
454 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000455 if (StartOfStringLiteral != Other.StartOfStringLiteral)
456 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000457 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000458 }
459 };
460
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000461 /// \brief Appends the next token to \p State and updates information
462 /// necessary for indentation.
463 ///
464 /// Puts the token on the current line if \p Newline is \c true and adds a
465 /// line break and necessary indentation otherwise.
466 ///
467 /// If \p DryRun is \c false, also creates and stores the required
468 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000469 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000470 const AnnotatedToken &Current = *State.NextToken;
471 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000472 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000473
Daniel Jasper4b866272013-02-01 11:00:45 +0000474 if (Current.Type == TT_ImplicitStringLiteral) {
475 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
476 State.NextToken->FormatTok.TokenLength;
477 if (State.NextToken->Children.empty())
478 State.NextToken = NULL;
479 else
480 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000481 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000482 }
483
Daniel Jasperf7935112012-12-03 18:12:45 +0000484 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000485 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000486 if (Current.is(tok::r_brace)) {
487 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000488 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000489 State.StartOfStringLiteral != 0) {
490 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000491 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000492 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000493 State.Stack.back().FirstLessLess != 0) {
494 State.Column = State.Stack.back().FirstLessLess;
495 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000496 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000497 Current.is(tok::period) || Current.is(tok::arrow) ||
498 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000499 // Indent and extra 4 spaces after if we know the current expression is
500 // continued. Don't do that on the top level, as we already indent 4
501 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000502 State.Column = std::max(State.Stack.back().LastSpace,
503 State.Stack.back().Indent) + 4;
504 } else if (Current.Type == TT_ConditionalExpr) {
505 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000506 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000507 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
508 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000509 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000510 } else if (Previous.ClosesTemplateDeclaration ||
511 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000512 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000513 } else if (Current.Type == TT_ObjCSelectorName) {
514 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
515 State.Column =
516 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
517 } else {
518 State.Column = State.Stack.back().Indent;
519 State.Stack.back().ColonPos =
520 State.Column + Current.FormatTok.TokenLength;
521 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000522 } else if (Previous.Type == TT_ObjCMethodExpr ||
523 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000524 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000525 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000526 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000527 }
528
Daniel Jasper54a86022013-02-15 11:07:25 +0000529 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000530 State.Stack.back().BreakBeforeParameter = true;
531 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
532 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000533 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000534
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000535 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000536 unsigned NewLines = 1;
537 if (Current.Type == TT_LineComment)
538 NewLines =
539 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
540 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000541 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000542 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000543 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000544 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000545 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000546 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000547 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000548
Daniel Jasper400adc62013-02-08 15:28:42 +0000549 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000550 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000551 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000552 State.Stack.back().Indent += 2;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000553
554 // Any break on this level means that the parent level has been broken
555 // and we need to avoid bin packing there.
556 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
557 State.Stack[i].BreakBeforeParameter = true;
558 }
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000559 if (Current.is(tok::period) || Current.is(tok::arrow))
560 State.Stack.back().BreakBeforeParameter = true;
561
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000562 // If we break after {, we should also break before the corresponding }.
563 if (Previous.is(tok::l_brace))
564 State.Stack.back().BreakBeforeClosingBrace = true;
565
566 if (State.Stack.back().AvoidBinPacking) {
567 // If we are breaking after '(', '{', '<', this is not bin packing
568 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000569 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000570 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
571 Line.MustBeDeclaration))
572 State.Stack.back().BreakBeforeParameter = true;
573 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000574 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000575 // FIXME: Put VariablePos into ParenState and remove second part of if().
576 if (Current.is(tok::equal) &&
577 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000578 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000579
Daniel Jaspereef30492013-02-11 12:36:37 +0000580 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000581
Daniel Jasperf7935112012-12-03 18:12:45 +0000582 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000583 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000584
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000585 if (Current.Type == TT_ObjCSelectorName &&
586 State.Stack.back().ColonPos == 0) {
587 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
588 State.Column + Spaces + Current.FormatTok.TokenLength)
589 State.Stack.back().ColonPos =
590 State.Stack.back().Indent + Current.LongestObjCSelectorName;
591 else
592 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000593 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000594 }
595
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000596 if (Current.Type != TT_LineComment &&
597 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
598 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000599 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000600 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000601 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000602
Daniel Jaspere9de2602012-12-06 09:56:08 +0000603 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000604 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
605 // Treat the condition inside an if as if it was a second function
606 // parameter, i.e. let nested calls have an indent of 4.
607 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000608 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000609 // Top-level spaces are exempt as that mostly leads to better results.
610 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000611 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000612 Previous.Type == TT_ConditionalExpr ||
613 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000614 getPrecedence(Previous) != prec::Assignment)
615 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000616 else if (Previous.Type == TT_InheritanceColon)
617 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000618 else if (Previous.ParameterCount > 1 &&
619 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000620 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000621 Previous.Type == TT_TemplateOpener))
622 // If this function has multiple parameters, indent nested calls from
623 // the start of the first parameter.
624 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000625 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
626 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
627 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000629
Manuel Klimek1998ea22013-02-20 10:15:13 +0000630 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000631 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000632
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000633 /// \brief Mark the next token as consumed in \p State and modify its stacks
634 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000635 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000636 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000637 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000638
Daniel Jaspereead02b2013-02-14 08:42:54 +0000639 if (Current.Type == TT_InheritanceColon)
640 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000641 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
642 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000643 if (Current.is(tok::question))
644 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000645 if (Current.Type == TT_CtorInitializerColon) {
646 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
647 State.Stack.back().AvoidBinPacking = true;
648 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000649 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000650
Daniel Jasper400adc62013-02-08 15:28:42 +0000651 // Insert scopes created by fake parenthesis.
652 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
653 ParenState NewParenState = State.Stack.back();
654 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000655 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000656 State.Stack.push_back(NewParenState);
657 }
658
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000659 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000660 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000661 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
662 Current.is(tok::l_brace) ||
663 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000664 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000665 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000666 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000667 NewIndent = 2 + State.Stack.back().LastSpace;
668 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000669 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000670 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperead41b62013-02-28 09:39:12 +0000671 AvoidBinPacking =
672 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000673 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000674 State.Stack.push_back(
675 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
676 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000677 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000678 }
679
Daniel Jasperacc33662013-02-08 08:22:00 +0000680 // If this '[' opens an ObjC call, determine whether all parameters fit into
681 // one line and put one per line if they don't.
682 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
683 Current.MatchingParen != NULL) {
684 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
685 State.Stack.back().BreakBeforeParameter = true;
686 }
687
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000688 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000689 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000690 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
691 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
692 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000693 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000694 --State.ParenLevel;
695 }
696
697 // Remove scopes created by fake parenthesis.
698 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
699 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000701
Manuel Klimek0c915712013-02-20 15:32:58 +0000702 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000703 State.StartOfStringLiteral = State.Column;
704 } else if (Current.isNot(tok::comment)) {
705 State.StartOfStringLiteral = 0;
706 }
707
Manuel Klimek1998ea22013-02-20 10:15:13 +0000708 State.Column += Current.FormatTok.TokenLength;
709
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000710 if (State.NextToken->Children.empty())
711 State.NextToken = NULL;
712 else
713 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000714
Manuel Klimek1998ea22013-02-20 10:15:13 +0000715 return breakProtrudingToken(Current, State, DryRun);
716 }
717
718 /// \brief If the current token sticks out over the end of the line, break
719 /// it if possible.
720 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
721 bool DryRun) {
722 if (Current.isNot(tok::string_literal))
723 return 0;
724
725 unsigned Penalty = 0;
726 unsigned TailOffset = 0;
727 unsigned TailLength = Current.FormatTok.TokenLength;
728 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
729 unsigned OffsetFromStart = 0;
730 while (StartColumn + TailLength > getColumnLimit()) {
731 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
732 TailOffset, TailLength);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000733 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekb176cff2013-03-01 13:14:08 +0000734 break;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000735 StringRef::size_type SplitPoint = getSplitPoint(
736 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000737 if (SplitPoint == StringRef::npos)
738 break;
739 assert(SplitPoint != 0);
740 // +2, because 'Text' starts after the opening quotes, and does not
741 // include the closing quote we need to insert.
742 unsigned WhitespaceStartColumn =
743 StartColumn + OffsetFromStart + SplitPoint + 2;
744 State.Stack.back().LastSpace = StartColumn;
745 if (!DryRun) {
746 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
747 Line.InPPDirective, StartColumn,
748 WhitespaceStartColumn, Style);
749 }
750 TailOffset += SplitPoint + 1;
751 TailLength -= SplitPoint + 1;
752 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000753 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000754 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
755 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000756 }
757 State.Column = StartColumn + TailLength;
758 return Penalty;
759 }
760
761 StringRef::size_type
762 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekb176cff2013-03-01 13:14:08 +0000763 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000764 if (SpaceOffset != StringRef::npos)
765 return SpaceOffset;
766 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
767 if (SlashOffset != StringRef::npos)
768 return SlashOffset;
769 if (Offset > 1)
770 // Do not split at 0.
Manuel Klimekb176cff2013-03-01 13:14:08 +0000771 return Offset - 1;
Manuel Klimeke317d1b2013-03-01 13:29:19 +0000772 return StringRef::npos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000773 }
774
Daniel Jasper2df93312013-01-09 10:16:05 +0000775 unsigned getColumnLimit() {
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000776 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000777 }
778
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000779 /// \brief An edge in the solution space from \c Previous->State to \c State,
780 /// inserting a newline dependent on the \c NewLine.
781 struct StateNode {
782 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000783 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000784 LineState State;
785 bool NewLine;
786 StateNode *Previous;
787 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000788
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000789 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
790 ///
791 /// In case of equal penalties, we want to prefer states that were inserted
792 /// first. During state generation we make sure that we insert states first
793 /// that break the line as late as possible.
794 typedef std::pair<unsigned, unsigned> OrderedPenalty;
795
796 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
797 /// \c State has the given \c OrderedPenalty.
798 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
799
800 /// \brief The BFS queue type.
801 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
802 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000803
804 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000805 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000806 /// This implements a variant of Dijkstra's algorithm on the graph that spans
807 /// the solution space (\c LineStates are the nodes). The algorithm tries to
808 /// find the shortest path (the one with lowest penalty) from \p InitialState
809 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000810 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000811 std::set<LineState> Seen;
812
Daniel Jasper4b866272013-02-01 11:00:45 +0000813 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000814 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000815 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
816 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
817 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000818
819 // While not empty, take first element and follow edges.
820 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000821 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000822 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000823 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000824 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000825 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000826 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000827 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000828
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000829 if (!Seen.insert(Node->State).second)
830 // State already examined with lower penalty.
831 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000832
Manuel Klimekaf491072013-02-13 10:54:19 +0000833 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
834 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000835 }
836
837 if (Queue.empty())
838 // We were unable to find a solution, do nothing.
839 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 return 0;
841
Daniel Jasper4b866272013-02-01 11:00:45 +0000842 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000843 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000844 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000845
Daniel Jasper4b866272013-02-01 11:00:45 +0000846 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000847 return Queue.top().second->State.Column;
848 }
849
850 void reconstructPath(LineState &State, StateNode *Current) {
851 // FIXME: This recursive implementation limits the possible number
852 // of tokens per line if compiled into a binary with small stack space.
853 // To become more independent of stack frame limitations we would need
854 // to also change the TokenAnnotator.
855 if (Current->Previous == NULL)
856 return;
857 reconstructPath(State, Current->Previous);
858 DEBUG({
859 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000860 llvm::errs()
861 << "Penalty for splitting before "
862 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
863 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000864 }
865 });
866 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000867 }
868
Manuel Klimekaf491072013-02-13 10:54:19 +0000869 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000870 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000871 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000872 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000873 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
874 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000875 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000876 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000877 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000878 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000879 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000880 Penalty += PreviousNode->State.NextToken->SplitPenalty;
881
882 StateNode *Node = new (Allocator.Allocate())
883 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000884 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000885 if (Node->State.Column > getColumnLimit()) {
886 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000887 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000888 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000889
890 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
891 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000892 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000893
Daniel Jasper4b866272013-02-01 11:00:45 +0000894 /// \brief Returns \c true, if a line break after \p State is allowed.
895 bool canBreak(const LineState &State) {
896 if (!State.NextToken->CanBreakBefore &&
897 !(State.NextToken->is(tok::r_brace) &&
898 State.Stack.back().BreakBeforeClosingBrace))
899 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000900 // This prevents breaks like:
901 // ...
902 // SomeParameter, OtherParameter).DoSomething(
903 // ...
904 // As they hide "DoSomething" and generally bad for readability.
905 if (State.NextToken->Parent->is(tok::l_paren) &&
906 State.ParenLevel <= State.StartOfLineLevel)
907 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000908 // Trying to insert a parameter on a new line if there are already more than
909 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000910 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000911 State.Stack.back().AvoidBinPacking)
912 return false;
913 return true;
914 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000915
Daniel Jasper4b866272013-02-01 11:00:45 +0000916 /// \brief Returns \c true, if a line break after \p State is mandatory.
917 bool mustBreak(const LineState &State) {
918 if (State.NextToken->MustBreakBefore)
919 return true;
920 if (State.NextToken->is(tok::r_brace) &&
921 State.Stack.back().BreakBeforeClosingBrace)
922 return true;
923 if (State.NextToken->Parent->is(tok::semi) &&
924 State.LineContainsContinuedForLoopSection)
925 return true;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000926 if ((State.NextToken->Parent->is(tok::comma) ||
927 State.NextToken->Parent->is(tok::semi) ||
928 State.NextToken->is(tok::question) ||
929 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000930 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000931 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000932 State.NextToken->isNot(tok::r_paren) &&
933 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000934 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000935 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
936 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000937 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000938 State.NextToken->LongestObjCSelectorName == 0 &&
939 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000940 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000941 if ((State.NextToken->Type == TT_CtorInitializerColon ||
942 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000943 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000944 return true;
945 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000946 }
947
Daniel Jasperf7935112012-12-03 18:12:45 +0000948 FormatStyle Style;
949 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000950 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000951 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000952 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000953 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000954
955 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
956 QueueType Queue;
957 // Increasing count of \c StateNode items we have created. This is used
958 // to create a deterministic order independent of the container.
959 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000960};
961
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000962class LexerBasedFormatTokenSource : public FormatTokenSource {
963public:
964 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000965 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000966 IdentTable(Lex.getLangOpts()) {
967 Lex.SetKeepWhitespaceMode(true);
968 }
969
970 virtual FormatToken getNextToken() {
971 if (GreaterStashed) {
972 FormatTok.NewlinesBefore = 0;
973 FormatTok.WhiteSpaceStart =
974 FormatTok.Tok.getLocation().getLocWithOffset(1);
975 FormatTok.WhiteSpaceLength = 0;
976 GreaterStashed = false;
977 return FormatTok;
978 }
979
980 FormatTok = FormatToken();
981 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000982 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000983 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000984 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
985 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000986
987 // Consume and record whitespace until we find a significant token.
988 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000989 unsigned Newlines = Text.count('\n');
990 unsigned EscapedNewlines = Text.count("\\\n");
991 FormatTok.NewlinesBefore += Newlines;
992 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000993 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
994
995 if (FormatTok.Tok.is(tok::eof))
996 return FormatTok;
997 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000998 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000999 }
Manuel Klimekef920692013-01-07 07:56:50 +00001000
1001 // Now FormatTok is the next non-whitespace token.
1002 FormatTok.TokenLength = Text.size();
1003
Manuel Klimek1abf7892013-01-04 23:34:14 +00001004 // In case the token starts with escaped newlines, we want to
1005 // take them into account as whitespace - this pattern is quite frequent
1006 // in macro definitions.
1007 // FIXME: What do we want to do with other escaped spaces, and escaped
1008 // spaces or newlines in the middle of tokens?
1009 // FIXME: Add a more explicit test.
1010 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001011 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001012 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001013 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001014 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001015 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001016 }
1017
1018 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001019 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001020 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001021 FormatTok.Tok.setKind(Info.getTokenID());
1022 }
1023
1024 if (FormatTok.Tok.is(tok::greatergreater)) {
1025 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +00001026 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001027 GreaterStashed = true;
1028 }
1029
Daniel Jasper3324cbe2013-03-01 16:45:59 +00001030 // If we reformat comments, we remove trailing whitespace. Update the length
1031 // accordingly.
1032 if (FormatTok.Tok.is(tok::comment))
1033 FormatTok.TokenLength = Text.rtrim().size();
1034
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001035 return FormatTok;
1036 }
1037
Nico Weber29f9dea2013-02-11 15:32:15 +00001038 IdentifierTable &getIdentTable() { return IdentTable; }
1039
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001040private:
1041 FormatToken FormatTok;
1042 bool GreaterStashed;
1043 Lexer &Lex;
1044 SourceManager &SourceMgr;
1045 IdentifierTable IdentTable;
1046
1047 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001048 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001049 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1050 Tok.getLength());
1051 }
1052};
1053
Daniel Jasperf7935112012-12-03 18:12:45 +00001054class Formatter : public UnwrappedLineConsumer {
1055public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001056 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1057 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001059 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001060 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001061
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001062 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001063
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001064 void deriveLocalStyle() {
1065 unsigned CountBoundToVariable = 0;
1066 unsigned CountBoundToType = 0;
1067 bool HasCpp03IncompatibleFormat = false;
1068 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1069 if (AnnotatedLines[i].First.Children.empty())
1070 continue;
1071 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1072 while (!Tok->Children.empty()) {
1073 if (Tok->Type == TT_PointerOrReference) {
1074 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1075 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1076 if (SpacesBefore && !SpacesAfter)
1077 ++CountBoundToVariable;
1078 else if (!SpacesBefore && SpacesAfter)
1079 ++CountBoundToType;
1080 }
1081
Daniel Jasper400adc62013-02-08 15:28:42 +00001082 if (Tok->Type == TT_TemplateCloser &&
1083 Tok->Parent->Type == TT_TemplateCloser &&
1084 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001085 HasCpp03IncompatibleFormat = true;
1086 Tok = &Tok->Children[0];
1087 }
1088 }
1089 if (Style.DerivePointerBinding) {
1090 if (CountBoundToType > CountBoundToVariable)
1091 Style.PointerBindsToType = true;
1092 else if (CountBoundToType < CountBoundToVariable)
1093 Style.PointerBindsToType = false;
1094 }
1095 if (Style.Standard == FormatStyle::LS_Auto) {
1096 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1097 : FormatStyle::LS_Cpp03;
1098 }
1099 }
1100
Daniel Jasperf7935112012-12-03 18:12:45 +00001101 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001102 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001103 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001104 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001105 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001106 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1107 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001108 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001109 Annotator.annotate(AnnotatedLines[i]);
1110 }
1111 deriveLocalStyle();
1112 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1113 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001114 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001115 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001116 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001117 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1118 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001119 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001120 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001121 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001122 while (IndentForLevel.size() <= TheLine.Level)
1123 IndentForLevel.push_back(-1);
1124 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001125 bool WasMoved =
1126 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1127 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001128 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001129 unsigned Indent = LevelIndent;
1130 if (static_cast<int>(Indent) + Offset >= 0)
1131 Indent += Offset;
1132 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1133 StructuralError) {
1134 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1135 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1136 } else {
1137 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1138 PreviousEndOfLineColumn);
1139 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001140 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001141 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001142 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001143 StructuralError);
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001144 PreviousEndOfLineColumn =
1145 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001146 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001147 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001148 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001149 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1150 TheLine.First.FormatTok.IsFirst) {
1151 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1152 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1153 unsigned LevelIndent = Indent;
1154 if (static_cast<int>(LevelIndent) - Offset >= 0)
1155 LevelIndent -= Offset;
1156 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001157
1158 // Remove trailing whitespace of the previous line if it was touched.
1159 if (PreviousLineWasTouched)
1160 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1161 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001162 }
Daniel Jasper24570102013-02-14 09:58:41 +00001163 // If we did not reformat this unwrapped line, the column at the end of
1164 // the last token is unchanged - thus, we can calculate the end of the
1165 // last token.
1166 PreviousEndOfLineColumn =
1167 SourceMgr.getSpellingColumnNumber(
1168 TheLine.Last->FormatTok.Tok.getLocation()) +
1169 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1170 SourceMgr, Lex.getLangOpts()) - 1;
1171 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001172 }
1173 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001174 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001175 }
1176
1177private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001178 /// \brief Get the indent of \p Level from \p IndentForLevel.
1179 ///
1180 /// \p IndentForLevel must contain the indent for the level \c l
1181 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1182 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001183 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001184 if (IndentForLevel[Level] != -1)
1185 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001186 if (Level == 0)
1187 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001188 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001189 }
1190
1191 /// \brief Get the offset of the line relatively to the level.
1192 ///
1193 /// For example, 'public:' labels in classes are offset by 1 or 2
1194 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001195 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001196 bool IsAccessModifier = false;
1197 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1198 RootToken.is(tok::kw_private))
1199 IsAccessModifier = true;
1200 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1201 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1202 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1203 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1204 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1205 IsAccessModifier = true;
1206
1207 if (IsAccessModifier)
1208 return Style.AccessModifierOffset;
1209 return 0;
1210 }
1211
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001212 /// \brief Tries to merge lines into one.
1213 ///
1214 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1215 /// if possible; note that \c I will be incremented when lines are merged.
1216 ///
1217 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001218 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001219 std::vector<AnnotatedLine>::iterator &I,
1220 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001221 // We can never merge stuff if there are trailing line comments.
1222 if (I->Last->Type == TT_LineComment)
1223 return;
1224
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001225 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001226 // If we already exceed the column limit, we set 'Limit' to 0. The different
1227 // tryMerge..() functions can then decide whether to still do merging.
1228 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001229
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001230 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001231 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001232
Daniel Jasper25837aa2013-01-14 14:14:23 +00001233 if (I->Last->is(tok::l_brace)) {
1234 tryMergeSimpleBlock(I, E, Limit);
1235 } else if (I->First.is(tok::kw_if)) {
1236 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001237 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1238 I->First.FormatTok.IsFirst)) {
1239 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001240 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001241 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001242 }
1243
Daniel Jasper39825ea2013-01-14 15:40:57 +00001244 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1245 std::vector<AnnotatedLine>::iterator E,
1246 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001247 if (Limit == 0)
1248 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001249 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001250 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1251 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001252 if (I + 2 != E && (I + 2)->InPPDirective &&
1253 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1254 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001255 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001256 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001257 join(Line, *(++I));
1258 }
1259
Daniel Jasper25837aa2013-01-14 14:14:23 +00001260 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1261 std::vector<AnnotatedLine>::iterator E,
1262 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001263 if (Limit == 0)
1264 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001265 if (!Style.AllowShortIfStatementsOnASingleLine)
1266 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001267 if ((I + 1)->InPPDirective != I->InPPDirective ||
1268 ((I + 1)->InPPDirective &&
1269 (I + 1)->First.FormatTok.HasUnescapedNewline))
1270 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001271 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001272 if (Line.Last->isNot(tok::r_paren))
1273 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001274 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001275 return;
1276 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1277 return;
1278 // Only inline simple if's (no nested if or else).
1279 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1280 return;
1281 join(Line, *(++I));
1282 }
1283
1284 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001285 std::vector<AnnotatedLine>::iterator E,
1286 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001287 // First, check that the current line allows merging. This is the case if
1288 // we're not in a control flow statement and the last token is an opening
1289 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001290 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001291 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001292 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1293 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1294 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1295 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001296 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001297 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1298 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001299 if (!AllowedTokens)
1300 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001301
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001302 AnnotatedToken *Tok = &(I + 1)->First;
1303 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001304 !Tok->MustBreakBefore) {
1305 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001306 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001307 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001308 join(Line, *(I + 1));
1309 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001310 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001311 // Check that we still have three lines and they fit into the limit.
1312 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1313 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001314 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001315
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001316 // Second, check that the next line does not contain any braces - if it
1317 // does, readability declines when putting it into a single line.
1318 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1319 return;
1320 do {
1321 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1322 return;
1323 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1324 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001325
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001326 // Last, check that the third line contains a single closing brace.
1327 Tok = &(I + 2)->First;
1328 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1329 Tok->MustBreakBefore)
1330 return;
1331
1332 join(Line, *(I + 1));
1333 join(Line, *(I + 2));
1334 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001335 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001336 }
1337
1338 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1339 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001340 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1341 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001342 }
1343
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001344 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001345 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001346 A.Last->Children.push_back(B.First);
1347 while (!A.Last->Children.empty()) {
1348 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001349 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001350 A.Last = &A.Last->Children[0];
1351 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001352 }
1353
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001354 bool touchesRanges(const AnnotatedLine &TheLine) {
1355 const FormatToken *First = &TheLine.First.FormatTok;
1356 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001357 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001358 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001359 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001360 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1361 Ranges[i].getBegin()) &&
1362 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1363 LineRange.getBegin()))
1364 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001365 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001366 return false;
1367 }
1368
1369 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001370 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001371 }
1372
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001373 /// \brief Add a new line and the required indent before the first Token
1374 /// of the \c UnwrappedLine if there was no structural parsing error.
1375 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001376 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1377 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001378 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001379
Daniel Jasperbbc84152013-01-29 11:27:30 +00001380 unsigned Newlines =
1381 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001382 if (Newlines == 0 && !Tok.IsFirst)
1383 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001384
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001385 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001386 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001387 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001388 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1389 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001390 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001391 }
1392
Alexander Kornienko116ba682013-01-14 11:34:14 +00001393 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001394 FormatStyle Style;
1395 Lexer &Lex;
1396 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001397 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001398 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001399 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001400 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001401};
1402
Daniel Jasperbbc84152013-01-29 11:27:30 +00001403tooling::Replacements
1404reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1405 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001406 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001407 OwningPtr<DiagnosticConsumer> DiagPrinter;
1408 if (DiagClient == 0) {
1409 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1410 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1411 DiagClient = DiagPrinter.get();
1412 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001413 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001414 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001415 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001416 Diagnostics.setSourceManager(&SourceMgr);
1417 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001418 return formatter.format();
1419}
1420
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001421LangOptions getFormattingLangOpts() {
1422 LangOptions LangOpts;
1423 LangOpts.CPlusPlus = 1;
1424 LangOpts.CPlusPlus11 = 1;
1425 LangOpts.Bool = 1;
1426 LangOpts.ObjC1 = 1;
1427 LangOpts.ObjC2 = 1;
1428 return LangOpts;
1429}
1430
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001431} // namespace format
1432} // namespace clang