blob: 2bd533222769b2161d7ce72142c49cd932f480ba [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 Jasper9278eb92013-01-16 14:59:02 +000064 GoogleStyle.BinPackParameters = false;
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 Jasper7fce3ab2013-02-06 14:22:40 +000077 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
78 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000079 return ChromiumStyle;
80}
81
Daniel Jasper94f0e132013-02-06 20:07:35 +000082static bool isTrailingComment(const AnnotatedToken &Tok) {
83 return Tok.is(tok::comment) &&
84 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
85}
86
Daniel Jasperacc33662013-02-08 08:22:00 +000087// Returns the length of everything up to the first possible line break after
88// the ), ], } or > matching \c Tok.
89static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
90 if (Tok.MatchingParen == NULL)
91 return 0;
92 AnnotatedToken *End = Tok.MatchingParen;
93 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
94 End = &End->Children[0];
95 }
96 return End->TotalLength - Tok.TotalLength + 1;
97}
98
Daniel Jasperaa701fa2013-01-18 08:44:07 +000099/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000100///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000101/// This includes special handling for certain constructs, e.g. the alignment of
102/// trailing line comments.
103class WhitespaceManager {
104public:
105 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
106
107 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
108 /// each \c AnnotatedToken.
109 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
110 unsigned Spaces, unsigned WhitespaceStartColumn,
111 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000112 // 2+ newlines mean an empty line separating logic scopes.
113 if (NewLines >= 2)
114 alignComments();
115
116 // Align line comments if they are trailing or if they continue other
117 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000118 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000119 if (Style.ColumnLimit >=
120 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
121 Comments.push_back(StoredComment());
122 Comments.back().Tok = Tok.FormatTok;
123 Comments.back().Spaces = Spaces;
124 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000125 if (NewLines == 0)
126 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
127 else
128 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000129 Comments.back().MaxColumn =
Daniel Jasper525264c2013-02-13 19:25:54 +0000130 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 return;
132 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000134
135 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000136 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000137 alignComments();
Manuel Klimek1998ea22013-02-20 10:15:13 +0000138 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000139 }
140
141 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
142 /// backslashes to escape newlines inside a preprocessor directive.
143 ///
144 /// This function and \c replaceWhitespace have the same behavior if
145 /// \c Newlines == 0.
146 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
147 unsigned Spaces, unsigned WhitespaceStartColumn,
148 const FormatStyle &Style) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000149 storeReplacement(
150 Tok.FormatTok,
151 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
152 }
153
154 /// \brief Inserts a line break into the middle of a token.
155 ///
156 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
157 /// break and \p Postfix before the rest of the token starts in the next line.
158 ///
159 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
160 /// used to generate the correct line break.
161 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
162 StringRef Postfix, bool InPPDirective, unsigned Spaces,
163 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
164 std::string NewLineText;
165 if (!InPPDirective)
166 NewLineText = getNewLineText(1, Spaces);
167 else
168 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
169 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
170 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
171 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
172 Replaces.insert(
173 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
174 }
175
176 /// \brief Returns all the \c Replacements created during formatting.
177 const tooling::Replacements &generateReplacements() {
178 alignComments();
179 return Replaces;
180 }
181
182private:
183 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
184 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
185 }
186
187 std::string
188 getNewLineText(unsigned NewLines, unsigned Spaces,
189 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000190 std::string NewLineText;
191 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000192 unsigned Offset =
193 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000194 for (unsigned i = 0; i < NewLines; ++i) {
195 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
196 NewLineText += "\\\n";
197 Offset = 0;
198 }
199 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000200 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000201 }
202
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000203 /// \brief Structure to store a comment for later layout and alignment.
204 struct StoredComment {
205 FormatToken Tok;
206 unsigned MinColumn;
207 unsigned MaxColumn;
208 unsigned NewLines;
209 unsigned Spaces;
210 };
211 SmallVector<StoredComment, 16> Comments;
212 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
213
214 /// \brief Try to align all stashed comments.
215 void alignComments() {
216 unsigned MinColumn = 0;
217 unsigned MaxColumn = UINT_MAX;
218 comment_iterator Start = Comments.begin();
219 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
220 ++I) {
221 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
222 alignComments(Start, I, MinColumn);
223 MinColumn = I->MinColumn;
224 MaxColumn = I->MaxColumn;
225 Start = I;
226 } else {
227 MinColumn = std::max(MinColumn, I->MinColumn);
228 MaxColumn = std::min(MaxColumn, I->MaxColumn);
229 }
230 }
231 alignComments(Start, Comments.end(), MinColumn);
232 Comments.clear();
233 }
234
235 /// \brief Put all the comments between \p I and \p E into \p Column.
236 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
237 while (I != E) {
238 unsigned Spaces = I->Spaces + Column - I->MinColumn;
239 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper400adc62013-02-08 15:28:42 +0000240 std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000241 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000242 }
243 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000244
245 /// \brief Stores \p Text as the replacement for the whitespace in front of
246 /// \p Tok.
247 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000248 // Don't create a replacement, if it does not change anything.
249 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
250 Tok.WhiteSpaceLength) == Text)
251 return;
252
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000253 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
254 Tok.WhiteSpaceLength, Text));
255 }
256
257 SourceManager &SourceMgr;
258 tooling::Replacements Replaces;
259};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000260
Daniel Jasper37905f72013-02-21 15:00:29 +0000261static bool isVarDeclName(const AnnotatedToken &Tok) {
262 return Tok.Parent != NULL && Tok.is(tok::identifier) &&
263 (Tok.Parent->Type == TT_PointerOrReference ||
264 Tok.Parent->is(tok::identifier));
265}
266
Daniel Jasperf7935112012-12-03 18:12:45 +0000267class UnwrappedLineFormatter {
268public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000269 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000270 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000271 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000272 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000273 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000274 FirstIndent(FirstIndent), RootToken(RootToken),
Manuel Klimekaf491072013-02-13 10:54:19 +0000275 Whitespaces(Whitespaces), Count(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000276 }
277
Manuel Klimek1abf7892013-01-04 23:34:14 +0000278 /// \brief Formats an \c UnwrappedLine.
279 ///
280 /// \returns The column after the last token in the last line of the
281 /// \c UnwrappedLine.
282 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000283 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000284 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000285 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000286 State.NextToken = &RootToken;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000287 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
288 !Style.BinPackParameters,
289 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000290 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000291 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000292 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000293 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000294 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000295
Manuel Klimek24998102013-01-16 14:55:28 +0000296 DEBUG({
297 DebugTokenState(*State.NextToken);
298 });
299
Daniel Jaspere9de2602012-12-06 09:56:08 +0000300 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000301 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000302
Daniel Jasper4b866272013-02-01 11:00:45 +0000303 // If everything fits on a single line, just put it there.
304 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
305 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000306 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000307 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000308 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000309 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000310
Daniel Jasperacc33662013-02-08 08:22:00 +0000311 // If the ObjC method declaration does not fit on a line, we should format
312 // it with one arg per line.
313 if (Line.Type == LT_ObjCMethodDecl)
314 State.Stack.back().BreakBeforeParameter = true;
315
Daniel Jasper4b866272013-02-01 11:00:45 +0000316 // Find best solution in solution space.
317 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000318 }
319
320private:
Manuel Klimek24998102013-01-16 14:55:28 +0000321 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
322 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000323 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
324 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000325 llvm::errs();
326 }
327
Daniel Jasper337816e2013-01-11 10:22:12 +0000328 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000329 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
330 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000331 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
332 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000333 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper54a86022013-02-15 11:07:25 +0000334 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
335 BreakBeforeThirdOperand(false) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000336 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000337
Daniel Jasperf7935112012-12-03 18:12:45 +0000338 /// \brief The position to which a specific parenthesis level needs to be
339 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000340 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000341
Daniel Jaspere9de2602012-12-06 09:56:08 +0000342 /// \brief The position of the last space on each level.
343 ///
344 /// Used e.g. to break like:
345 /// functionCall(Parameter, otherCall(
346 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000347 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000348
Daniel Jaspere9de2602012-12-06 09:56:08 +0000349 /// \brief The position the first "<<" operator encountered on each level.
350 ///
351 /// Used to align "<<" operators. 0 if no such operator has been encountered
352 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000353 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000354
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000355 /// \brief Whether a newline needs to be inserted before the block's closing
356 /// brace.
357 ///
358 /// We only want to insert a newline before the closing brace if there also
359 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000360 bool BreakBeforeClosingBrace;
361
Daniel Jasperca6623b2013-01-28 12:45:14 +0000362 /// \brief The column of a \c ? in a conditional expression;
363 unsigned QuestionColumn;
364
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000365 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
366 /// lines, in this context.
367 bool AvoidBinPacking;
368
369 /// \brief Break after the next comma (or all the commas in this context if
370 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000371 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000372
373 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000374 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000375
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000376 /// \brief The position of the colon in an ObjC method declaration/call.
377 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000378
Daniel Jasper54a86022013-02-15 11:07:25 +0000379 /// \brief Break before third operand in ternary expression.
380 bool BreakBeforeThirdOperand;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000381
Daniel Jasper337816e2013-01-11 10:22:12 +0000382 bool operator<(const ParenState &Other) const {
383 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000384 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000385 if (LastSpace != Other.LastSpace)
386 return LastSpace < Other.LastSpace;
387 if (FirstLessLess != Other.FirstLessLess)
388 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000389 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
390 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000391 if (QuestionColumn != Other.QuestionColumn)
392 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000393 if (AvoidBinPacking != Other.AvoidBinPacking)
394 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000395 if (BreakBeforeParameter != Other.BreakBeforeParameter)
396 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000397 if (HasMultiParameterLine != Other.HasMultiParameterLine)
398 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000399 if (ColonPos != Other.ColonPos)
400 return ColonPos < Other.ColonPos;
Daniel Jasper54a86022013-02-15 11:07:25 +0000401 if (BreakBeforeThirdOperand != Other.BreakBeforeThirdOperand)
402 return BreakBeforeThirdOperand;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000403 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000404 }
405 };
406
407 /// \brief The current state when indenting a unwrapped line.
408 ///
409 /// As the indenting tries different combinations this is copied by value.
410 struct LineState {
411 /// \brief The number of used columns in the current line.
412 unsigned Column;
413
414 /// \brief The token that needs to be next formatted.
415 const AnnotatedToken *NextToken;
416
Daniel Jasperbbc84152013-01-29 11:27:30 +0000417 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000418 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000419 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000420 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000421
422 /// \brief \c true if this line contains a continued for-loop section.
423 bool LineContainsContinuedForLoopSection;
424
Daniel Jasper400adc62013-02-08 15:28:42 +0000425 /// \brief The level of nesting inside (), [], <> and {}.
426 unsigned ParenLevel;
427
Daniel Jasper40c36c52013-02-18 11:05:07 +0000428 /// \brief The \c ParenLevel at the start of this line.
429 unsigned StartOfLineLevel;
430
Manuel Klimek02f640a2013-02-20 15:25:48 +0000431 /// \brief The start column of the string literal, if we're in a string
432 /// literal sequence, 0 otherwise.
433 unsigned StartOfStringLiteral;
434
Daniel Jasper337816e2013-01-11 10:22:12 +0000435 /// \brief A stack keeping track of properties applying to parenthesis
436 /// levels.
437 std::vector<ParenState> Stack;
438
439 /// \brief Comparison operator to be able to used \c LineState in \c map.
440 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000441 if (NextToken != Other.NextToken)
442 return NextToken < Other.NextToken;
443 if (Column != Other.Column)
444 return Column < Other.Column;
445 if (VariablePos != Other.VariablePos)
446 return VariablePos < Other.VariablePos;
447 if (LineContainsContinuedForLoopSection !=
448 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000449 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000450 if (ParenLevel != Other.ParenLevel)
451 return ParenLevel < Other.ParenLevel;
452 if (StartOfLineLevel != Other.StartOfLineLevel)
453 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000454 if (StartOfStringLiteral != Other.StartOfStringLiteral)
455 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000456 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000457 }
458 };
459
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000460 /// \brief Appends the next token to \p State and updates information
461 /// necessary for indentation.
462 ///
463 /// Puts the token on the current line if \p Newline is \c true and adds a
464 /// line break and necessary indentation otherwise.
465 ///
466 /// If \p DryRun is \c false, also creates and stores the required
467 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000468 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000469 const AnnotatedToken &Current = *State.NextToken;
470 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000471 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000472
Daniel Jasper4b866272013-02-01 11:00:45 +0000473 if (Current.Type == TT_ImplicitStringLiteral) {
474 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
475 State.NextToken->FormatTok.TokenLength;
476 if (State.NextToken->Children.empty())
477 State.NextToken = NULL;
478 else
479 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000480 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000481 }
482
Daniel Jasperf7935112012-12-03 18:12:45 +0000483 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000484 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000485 if (Current.is(tok::r_brace)) {
486 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000487 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000488 State.StartOfStringLiteral != 0) {
489 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000490 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000491 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000492 State.Stack.back().FirstLessLess != 0) {
493 State.Column = State.Stack.back().FirstLessLess;
494 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000495 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000496 Current.is(tok::period) || Current.is(tok::arrow) ||
497 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000498 // Indent and extra 4 spaces after if we know the current expression is
499 // continued. Don't do that on the top level, as we already indent 4
500 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000501 State.Column = std::max(State.Stack.back().LastSpace,
502 State.Stack.back().Indent) + 4;
503 } else if (Current.Type == TT_ConditionalExpr) {
504 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000505 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000506 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
507 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000508 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000509 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
510 Current.Type == TT_StartOfName) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000511 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000512 } else if (Current.Type == TT_ObjCSelectorName) {
513 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
514 State.Column =
515 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
516 } else {
517 State.Column = State.Stack.back().Indent;
518 State.Stack.back().ColonPos =
519 State.Column + Current.FormatTok.TokenLength;
520 }
Daniel Jasper37905f72013-02-21 15:00:29 +0000521 } else if (Previous.Type == TT_ObjCMethodExpr || isVarDeclName(Current)) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000522 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000523 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000524 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000525 }
526
Daniel Jasper54a86022013-02-15 11:07:25 +0000527 if (Current.is(tok::question))
528 State.Stack.back().BreakBeforeThirdOperand = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000529 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000530 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000531
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000532 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000534
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000535 if (!DryRun) {
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000536 unsigned NewLines =
537 std::max(1u, std::min(Current.FormatTok.NewlinesBefore,
538 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000539 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000540 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000541 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000542 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000543 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000544 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000545 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000546
Daniel Jasper400adc62013-02-08 15:28:42 +0000547 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000548 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000549 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000550 State.Stack.back().Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000551 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000552 if (Current.is(tok::equal) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000553 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000554 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000555
Daniel Jaspereef30492013-02-11 12:36:37 +0000556 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000559 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000560
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000561 if (Current.Type == TT_ObjCSelectorName &&
562 State.Stack.back().ColonPos == 0) {
563 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
564 State.Column + Spaces + Current.FormatTok.TokenLength)
565 State.Stack.back().ColonPos =
566 State.Stack.back().Indent + Current.LongestObjCSelectorName;
567 else
568 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000569 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000570 }
571
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000572 if (Current.Type != TT_LineComment &&
573 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
574 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000575 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000576 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000577 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000578
Daniel Jaspere9de2602012-12-06 09:56:08 +0000579 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000580 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
581 // Treat the condition inside an if as if it was a second function
582 // parameter, i.e. let nested calls have an indent of 4.
583 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000584 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000585 // Top-level spaces are exempt as that mostly leads to better results.
586 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000587 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000588 Previous.Type == TT_ConditionalExpr ||
589 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000590 getPrecedence(Previous) != prec::Assignment)
591 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000592 else if (Previous.Type == TT_InheritanceColon)
593 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000594 else if (Previous.ParameterCount > 1 &&
595 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000596 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000597 Previous.Type == TT_TemplateOpener))
598 // If this function has multiple parameters, indent nested calls from
599 // the start of the first parameter.
600 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000601 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
602 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
603 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000604 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000605
606 // If we break after an {, we should also break before the corresponding }.
607 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000608 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000609
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000610 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000611 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000612 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000613 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000614 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
615 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000616 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
617 Line.MustBeDeclaration))
Daniel Jasperacc33662013-02-08 08:22:00 +0000618 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper37905f72013-02-21 15:00:29 +0000619 }
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000620
Daniel Jasper37905f72013-02-21 15:00:29 +0000621 if (Newline) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000622 // Any break on this level means that the parent level has been broken
623 // and we need to avoid bin packing there.
624 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000625 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperacc33662013-02-08 08:22:00 +0000626 State.Stack[i].BreakBeforeParameter = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000627 }
628 }
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);
655 State.Stack.push_back(NewParenState);
656 }
657
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000658 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000659 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000660 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
661 Current.is(tok::l_brace) ||
662 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000663 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000664 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000665 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000666 NewIndent = 2 + State.Stack.back().LastSpace;
667 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000668 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000669 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000670 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000671 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000672 State.Stack.push_back(
673 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
674 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000675 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000676 }
677
Daniel Jasperacc33662013-02-08 08:22:00 +0000678 // If this '[' opens an ObjC call, determine whether all parameters fit into
679 // one line and put one per line if they don't.
680 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
681 Current.MatchingParen != NULL) {
682 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
683 State.Stack.back().BreakBeforeParameter = true;
684 }
685
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000686 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000687 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000688 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
689 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
690 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000691 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000692 --State.ParenLevel;
693 }
694
695 // Remove scopes created by fake parenthesis.
696 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
697 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000699
Manuel Klimek0c915712013-02-20 15:32:58 +0000700 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000701 State.StartOfStringLiteral = State.Column;
702 } else if (Current.isNot(tok::comment)) {
703 State.StartOfStringLiteral = 0;
704 }
705
Manuel Klimek1998ea22013-02-20 10:15:13 +0000706 State.Column += Current.FormatTok.TokenLength;
707
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000708 if (State.NextToken->Children.empty())
709 State.NextToken = NULL;
710 else
711 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000712
Manuel Klimek1998ea22013-02-20 10:15:13 +0000713 return breakProtrudingToken(Current, State, DryRun);
714 }
715
716 /// \brief If the current token sticks out over the end of the line, break
717 /// it if possible.
718 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
719 bool DryRun) {
720 if (Current.isNot(tok::string_literal))
721 return 0;
722
723 unsigned Penalty = 0;
724 unsigned TailOffset = 0;
725 unsigned TailLength = Current.FormatTok.TokenLength;
726 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
727 unsigned OffsetFromStart = 0;
728 while (StartColumn + TailLength > getColumnLimit()) {
729 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
730 TailOffset, TailLength);
731 StringRef::size_type SplitPoint =
732 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
733 if (SplitPoint == StringRef::npos)
734 break;
735 assert(SplitPoint != 0);
736 // +2, because 'Text' starts after the opening quotes, and does not
737 // include the closing quote we need to insert.
738 unsigned WhitespaceStartColumn =
739 StartColumn + OffsetFromStart + SplitPoint + 2;
740 State.Stack.back().LastSpace = StartColumn;
741 if (!DryRun) {
742 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
743 Line.InPPDirective, StartColumn,
744 WhitespaceStartColumn, Style);
745 }
746 TailOffset += SplitPoint + 1;
747 TailLength -= SplitPoint + 1;
748 OffsetFromStart = 1;
749 Penalty += 100;
750 }
751 State.Column = StartColumn + TailLength;
752 return Penalty;
753 }
754
755 StringRef::size_type
756 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
757 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
758 return Text.rfind(' ', Offset);
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 }
760
Daniel Jasper2df93312013-01-09 10:16:05 +0000761 unsigned getColumnLimit() {
762 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
763 }
764
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000765 /// \brief An edge in the solution space from \c Previous->State to \c State,
766 /// inserting a newline dependent on the \c NewLine.
767 struct StateNode {
768 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
769 : State(State), NewLine(NewLine), Previous(Previous) {
770 }
771 LineState State;
772 bool NewLine;
773 StateNode *Previous;
774 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000775
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000776 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
777 ///
778 /// In case of equal penalties, we want to prefer states that were inserted
779 /// first. During state generation we make sure that we insert states first
780 /// that break the line as late as possible.
781 typedef std::pair<unsigned, unsigned> OrderedPenalty;
782
783 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
784 /// \c State has the given \c OrderedPenalty.
785 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
786
787 /// \brief The BFS queue type.
788 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
789 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000790
791 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000792 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000793 /// This implements a variant of Dijkstra's algorithm on the graph that spans
794 /// the solution space (\c LineStates are the nodes). The algorithm tries to
795 /// find the shortest path (the one with lowest penalty) from \p InitialState
796 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000798 std::set<LineState> Seen;
799
Daniel Jasper4b866272013-02-01 11:00:45 +0000800 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000801 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000802 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
803 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
804 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000805
806 // While not empty, take first element and follow edges.
807 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000808 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000809 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000810 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000811 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000812 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000813 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000814 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000815
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000816 if (!Seen.insert(Node->State).second)
817 // State already examined with lower penalty.
818 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000819
Manuel Klimekaf491072013-02-13 10:54:19 +0000820 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
821 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000822 }
823
824 if (Queue.empty())
825 // We were unable to find a solution, do nothing.
826 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000827 return 0;
828
Daniel Jasper4b866272013-02-01 11:00:45 +0000829 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000830 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000831 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000832
Daniel Jasper4b866272013-02-01 11:00:45 +0000833 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000834 return Queue.top().second->State.Column;
835 }
836
837 void reconstructPath(LineState &State, StateNode *Current) {
838 // FIXME: This recursive implementation limits the possible number
839 // of tokens per line if compiled into a binary with small stack space.
840 // To become more independent of stack frame limitations we would need
841 // to also change the TokenAnnotator.
842 if (Current->Previous == NULL)
843 return;
844 reconstructPath(State, Current->Previous);
845 DEBUG({
846 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000847 llvm::errs()
848 << "Penalty for splitting before "
849 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
850 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 }
852 });
853 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000854 }
855
Manuel Klimekaf491072013-02-13 10:54:19 +0000856 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000857 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000858 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000859 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000860 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
861 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000862 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000863 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000864 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000865 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000866 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000867 Penalty += PreviousNode->State.NextToken->SplitPenalty;
868
869 StateNode *Node = new (Allocator.Allocate())
870 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000871 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000872 if (Node->State.Column > getColumnLimit()) {
873 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000874 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000875 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000876
877 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
878 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000879 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000880
Daniel Jasper4b866272013-02-01 11:00:45 +0000881 /// \brief Returns \c true, if a line break after \p State is allowed.
882 bool canBreak(const LineState &State) {
883 if (!State.NextToken->CanBreakBefore &&
884 !(State.NextToken->is(tok::r_brace) &&
885 State.Stack.back().BreakBeforeClosingBrace))
886 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000887 // This prevents breaks like:
888 // ...
889 // SomeParameter, OtherParameter).DoSomething(
890 // ...
891 // As they hide "DoSomething" and generally bad for readability.
892 if (State.NextToken->Parent->is(tok::l_paren) &&
893 State.ParenLevel <= State.StartOfLineLevel)
894 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000895 // Trying to insert a parameter on a new line if there are already more than
896 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000897 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000898 State.Stack.back().AvoidBinPacking)
899 return false;
900 return true;
901 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000902
Daniel Jasper4b866272013-02-01 11:00:45 +0000903 /// \brief Returns \c true, if a line break after \p State is mandatory.
904 bool mustBreak(const LineState &State) {
905 if (State.NextToken->MustBreakBefore)
906 return true;
907 if (State.NextToken->is(tok::r_brace) &&
908 State.Stack.back().BreakBeforeClosingBrace)
909 return true;
910 if (State.NextToken->Parent->is(tok::semi) &&
911 State.LineContainsContinuedForLoopSection)
912 return true;
913 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000914 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000915 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000916 State.NextToken->isNot(tok::r_paren) &&
917 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000918 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000919 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
920 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000921 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000922 State.NextToken->LongestObjCSelectorName == 0 &&
923 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000924 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000925 if ((State.NextToken->Type == TT_CtorInitializerColon ||
926 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000927 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000928 return true;
Daniel Jasper54a86022013-02-15 11:07:25 +0000929 if (State.NextToken->is(tok::colon) &&
930 State.Stack.back().BreakBeforeThirdOperand)
931 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000932 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000933 }
934
Daniel Jasperf7935112012-12-03 18:12:45 +0000935 FormatStyle Style;
936 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000937 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000938 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000939 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000940 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000941
942 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
943 QueueType Queue;
944 // Increasing count of \c StateNode items we have created. This is used
945 // to create a deterministic order independent of the container.
946 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000947};
948
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000949class LexerBasedFormatTokenSource : public FormatTokenSource {
950public:
951 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000952 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000953 IdentTable(Lex.getLangOpts()) {
954 Lex.SetKeepWhitespaceMode(true);
955 }
956
957 virtual FormatToken getNextToken() {
958 if (GreaterStashed) {
959 FormatTok.NewlinesBefore = 0;
960 FormatTok.WhiteSpaceStart =
961 FormatTok.Tok.getLocation().getLocWithOffset(1);
962 FormatTok.WhiteSpaceLength = 0;
963 GreaterStashed = false;
964 return FormatTok;
965 }
966
967 FormatTok = FormatToken();
968 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000969 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000970 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000971 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
972 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000973
974 // Consume and record whitespace until we find a significant token.
975 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000976 unsigned Newlines = Text.count('\n');
977 unsigned EscapedNewlines = Text.count("\\\n");
978 FormatTok.NewlinesBefore += Newlines;
979 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000980 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
981
982 if (FormatTok.Tok.is(tok::eof))
983 return FormatTok;
984 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000985 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000986 }
Manuel Klimekef920692013-01-07 07:56:50 +0000987
988 // Now FormatTok is the next non-whitespace token.
989 FormatTok.TokenLength = Text.size();
990
Manuel Klimek1abf7892013-01-04 23:34:14 +0000991 // In case the token starts with escaped newlines, we want to
992 // take them into account as whitespace - this pattern is quite frequent
993 // in macro definitions.
994 // FIXME: What do we want to do with other escaped spaces, and escaped
995 // spaces or newlines in the middle of tokens?
996 // FIXME: Add a more explicit test.
997 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000998 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000999 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001000 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001001 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001002 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001003 }
1004
1005 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001006 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001007 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001008 FormatTok.Tok.setKind(Info.getTokenID());
1009 }
1010
1011 if (FormatTok.Tok.is(tok::greatergreater)) {
1012 FormatTok.Tok.setKind(tok::greater);
1013 GreaterStashed = true;
1014 }
1015
1016 return FormatTok;
1017 }
1018
Nico Weber29f9dea2013-02-11 15:32:15 +00001019 IdentifierTable &getIdentTable() { return IdentTable; }
1020
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001021private:
1022 FormatToken FormatTok;
1023 bool GreaterStashed;
1024 Lexer &Lex;
1025 SourceManager &SourceMgr;
1026 IdentifierTable IdentTable;
1027
1028 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001029 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001030 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1031 Tok.getLength());
1032 }
1033};
1034
Daniel Jasperf7935112012-12-03 18:12:45 +00001035class Formatter : public UnwrappedLineConsumer {
1036public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001037 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1038 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001039 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001040 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001041 Whitespaces(SourceMgr), Ranges(Ranges) {
1042 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001043
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001044 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001045
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001046 void deriveLocalStyle() {
1047 unsigned CountBoundToVariable = 0;
1048 unsigned CountBoundToType = 0;
1049 bool HasCpp03IncompatibleFormat = false;
1050 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1051 if (AnnotatedLines[i].First.Children.empty())
1052 continue;
1053 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1054 while (!Tok->Children.empty()) {
1055 if (Tok->Type == TT_PointerOrReference) {
1056 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1057 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1058 if (SpacesBefore && !SpacesAfter)
1059 ++CountBoundToVariable;
1060 else if (!SpacesBefore && SpacesAfter)
1061 ++CountBoundToType;
1062 }
1063
Daniel Jasper400adc62013-02-08 15:28:42 +00001064 if (Tok->Type == TT_TemplateCloser &&
1065 Tok->Parent->Type == TT_TemplateCloser &&
1066 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001067 HasCpp03IncompatibleFormat = true;
1068 Tok = &Tok->Children[0];
1069 }
1070 }
1071 if (Style.DerivePointerBinding) {
1072 if (CountBoundToType > CountBoundToVariable)
1073 Style.PointerBindsToType = true;
1074 else if (CountBoundToType < CountBoundToVariable)
1075 Style.PointerBindsToType = false;
1076 }
1077 if (Style.Standard == FormatStyle::LS_Auto) {
1078 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1079 : FormatStyle::LS_Cpp03;
1080 }
1081 }
1082
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001084 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001085 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001086 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001087 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001088 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1089 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001090 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001091 Annotator.annotate(AnnotatedLines[i]);
1092 }
1093 deriveLocalStyle();
1094 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1095 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001096 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001097 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001098 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001099 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1100 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001101 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001102 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001103 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001104 while (IndentForLevel.size() <= TheLine.Level)
1105 IndentForLevel.push_back(-1);
1106 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001107 bool WasMoved =
1108 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1109 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001110 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001111 unsigned Indent = LevelIndent;
1112 if (static_cast<int>(Indent) + Offset >= 0)
1113 Indent += Offset;
1114 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1115 StructuralError) {
1116 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1117 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1118 } else {
1119 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1120 PreviousEndOfLineColumn);
1121 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001122 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001123 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001124 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001125 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001126 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001127 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001128 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001129 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001130 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1131 TheLine.First.FormatTok.IsFirst) {
1132 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1133 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1134 unsigned LevelIndent = Indent;
1135 if (static_cast<int>(LevelIndent) - Offset >= 0)
1136 LevelIndent -= Offset;
1137 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001138
1139 // Remove trailing whitespace of the previous line if it was touched.
1140 if (PreviousLineWasTouched)
1141 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1142 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001143 }
Daniel Jasper24570102013-02-14 09:58:41 +00001144 // If we did not reformat this unwrapped line, the column at the end of
1145 // the last token is unchanged - thus, we can calculate the end of the
1146 // last token.
1147 PreviousEndOfLineColumn =
1148 SourceMgr.getSpellingColumnNumber(
1149 TheLine.Last->FormatTok.Tok.getLocation()) +
1150 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1151 SourceMgr, Lex.getLangOpts()) - 1;
1152 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001153 }
1154 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001155 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001156 }
1157
1158private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001159 /// \brief Get the indent of \p Level from \p IndentForLevel.
1160 ///
1161 /// \p IndentForLevel must contain the indent for the level \c l
1162 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1163 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001164 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001165 if (IndentForLevel[Level] != -1)
1166 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001167 if (Level == 0)
1168 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001169 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001170 }
1171
1172 /// \brief Get the offset of the line relatively to the level.
1173 ///
1174 /// For example, 'public:' labels in classes are offset by 1 or 2
1175 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001176 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001177 bool IsAccessModifier = false;
1178 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1179 RootToken.is(tok::kw_private))
1180 IsAccessModifier = true;
1181 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1182 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1183 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1184 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1185 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1186 IsAccessModifier = true;
1187
1188 if (IsAccessModifier)
1189 return Style.AccessModifierOffset;
1190 return 0;
1191 }
1192
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001193 /// \brief Tries to merge lines into one.
1194 ///
1195 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1196 /// if possible; note that \c I will be incremented when lines are merged.
1197 ///
1198 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001199 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001200 std::vector<AnnotatedLine>::iterator &I,
1201 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001202 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1203
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001204 // We can never merge stuff if there are trailing line comments.
1205 if (I->Last->Type == TT_LineComment)
1206 return;
1207
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001208 // Check whether the UnwrappedLine can be put onto a single line. If
1209 // so, this is bound to be the optimal solution (by definition) and we
1210 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001211 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001212 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001213 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001214
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001215 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001216 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001217
Daniel Jasper25837aa2013-01-14 14:14:23 +00001218 if (I->Last->is(tok::l_brace)) {
1219 tryMergeSimpleBlock(I, E, Limit);
1220 } else if (I->First.is(tok::kw_if)) {
1221 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001222 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1223 I->First.FormatTok.IsFirst)) {
1224 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001225 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001226 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001227 }
1228
Daniel Jasper39825ea2013-01-14 15:40:57 +00001229 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1230 std::vector<AnnotatedLine>::iterator E,
1231 unsigned Limit) {
1232 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001233 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1234 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001235 if (I + 2 != E && (I + 2)->InPPDirective &&
1236 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1237 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001238 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001239 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001240 join(Line, *(++I));
1241 }
1242
Daniel Jasper25837aa2013-01-14 14:14:23 +00001243 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1244 std::vector<AnnotatedLine>::iterator E,
1245 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001246 if (!Style.AllowShortIfStatementsOnASingleLine)
1247 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001248 if ((I + 1)->InPPDirective != I->InPPDirective ||
1249 ((I + 1)->InPPDirective &&
1250 (I + 1)->First.FormatTok.HasUnescapedNewline))
1251 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001252 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001253 if (Line.Last->isNot(tok::r_paren))
1254 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001255 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001256 return;
1257 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1258 return;
1259 // Only inline simple if's (no nested if or else).
1260 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1261 return;
1262 join(Line, *(++I));
1263 }
1264
1265 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001266 std::vector<AnnotatedLine>::iterator E,
1267 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001268 // First, check that the current line allows merging. This is the case if
1269 // we're not in a control flow statement and the last token is an opening
1270 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001271 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001272 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001273 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1274 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1275 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1276 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001277 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001278 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1279 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001280 if (!AllowedTokens)
1281 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001282
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001283 AnnotatedToken *Tok = &(I + 1)->First;
1284 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1285 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jaspereef30492013-02-11 12:36:37 +00001286 Tok->SpacesRequiredBefore = 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001287 join(Line, *(I + 1));
1288 I += 1;
1289 } else {
1290 // Check that we still have three lines and they fit into the limit.
1291 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1292 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001293 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001294
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001295 // Second, check that the next line does not contain any braces - if it
1296 // does, readability declines when putting it into a single line.
1297 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1298 return;
1299 do {
1300 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1301 return;
1302 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1303 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001304
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001305 // Last, check that the third line contains a single closing brace.
1306 Tok = &(I + 2)->First;
1307 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1308 Tok->MustBreakBefore)
1309 return;
1310
1311 join(Line, *(I + 1));
1312 join(Line, *(I + 2));
1313 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001314 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001315 }
1316
1317 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1318 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001319 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1320 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001321 }
1322
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001323 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1324 A.Last->Children.push_back(B.First);
1325 while (!A.Last->Children.empty()) {
1326 A.Last->Children[0].Parent = A.Last;
1327 A.Last = &A.Last->Children[0];
1328 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001329 }
1330
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001331 bool touchesRanges(const AnnotatedLine &TheLine) {
1332 const FormatToken *First = &TheLine.First.FormatTok;
1333 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001334 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001335 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001336 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001337 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1338 Ranges[i].getBegin()) &&
1339 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1340 LineRange.getBegin()))
1341 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001342 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001343 return false;
1344 }
1345
1346 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001347 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001348 }
1349
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001350 /// \brief Add a new line and the required indent before the first Token
1351 /// of the \c UnwrappedLine if there was no structural parsing error.
1352 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001353 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1354 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001355 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001356
Daniel Jasperbbc84152013-01-29 11:27:30 +00001357 unsigned Newlines =
1358 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001359 if (Newlines == 0 && !Tok.IsFirst)
1360 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001361
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001362 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001363 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001364 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001365 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1366 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001367 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001368 }
1369
Alexander Kornienko116ba682013-01-14 11:34:14 +00001370 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001371 FormatStyle Style;
1372 Lexer &Lex;
1373 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001374 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001375 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001376 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001377 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001378};
1379
Daniel Jasperbbc84152013-01-29 11:27:30 +00001380tooling::Replacements
1381reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1382 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001383 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001384 OwningPtr<DiagnosticConsumer> DiagPrinter;
1385 if (DiagClient == 0) {
1386 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1387 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1388 DiagClient = DiagPrinter.get();
1389 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001390 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001391 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001392 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001393 Diagnostics.setSourceManager(&SourceMgr);
1394 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001395 return formatter.format();
1396}
1397
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001398LangOptions getFormattingLangOpts() {
1399 LangOptions LangOpts;
1400 LangOpts.CPlusPlus = 1;
1401 LangOpts.CPlusPlus11 = 1;
1402 LangOpts.Bool = 1;
1403 LangOpts.ObjC1 = 1;
1404 LangOpts.ObjC2 = 1;
1405 return LangOpts;
1406}
1407
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001408} // namespace format
1409} // namespace clang