blob: 44a91a96ecb94c1f9bc50f2b013db598308d065c [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 Jasperf7935112012-12-03 18:12:45 +0000261class UnwrappedLineFormatter {
262public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000263 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000264 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000265 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000266 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000267 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000268 FirstIndent(FirstIndent), RootToken(RootToken),
Manuel Klimekaf491072013-02-13 10:54:19 +0000269 Whitespaces(Whitespaces), Count(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000270 }
271
Manuel Klimek1abf7892013-01-04 23:34:14 +0000272 /// \brief Formats an \c UnwrappedLine.
273 ///
274 /// \returns The column after the last token in the last line of the
275 /// \c UnwrappedLine.
276 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000277 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000278 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000279 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000280 State.NextToken = &RootToken;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000281 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
282 !Style.BinPackParameters,
283 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000284 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000285 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000286 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000287 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000288 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000289
Manuel Klimek24998102013-01-16 14:55:28 +0000290 DEBUG({
291 DebugTokenState(*State.NextToken);
292 });
293
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000295 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000296
Daniel Jasper4b866272013-02-01 11:00:45 +0000297 // If everything fits on a single line, just put it there.
298 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
299 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000300 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000301 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000302 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000303 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000304
Daniel Jasperacc33662013-02-08 08:22:00 +0000305 // If the ObjC method declaration does not fit on a line, we should format
306 // it with one arg per line.
307 if (Line.Type == LT_ObjCMethodDecl)
308 State.Stack.back().BreakBeforeParameter = true;
309
Daniel Jasper4b866272013-02-01 11:00:45 +0000310 // Find best solution in solution space.
311 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000312 }
313
314private:
Manuel Klimek24998102013-01-16 14:55:28 +0000315 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
316 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000317 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
318 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000319 llvm::errs();
320 }
321
Daniel Jasper337816e2013-01-11 10:22:12 +0000322 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000323 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
324 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000325 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
326 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000327 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper54a86022013-02-15 11:07:25 +0000328 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
329 BreakBeforeThirdOperand(false) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000330 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000331
Daniel Jasperf7935112012-12-03 18:12:45 +0000332 /// \brief The position to which a specific parenthesis level needs to be
333 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000334 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000335
Daniel Jaspere9de2602012-12-06 09:56:08 +0000336 /// \brief The position of the last space on each level.
337 ///
338 /// Used e.g. to break like:
339 /// functionCall(Parameter, otherCall(
340 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000341 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000342
Daniel Jaspere9de2602012-12-06 09:56:08 +0000343 /// \brief The position the first "<<" operator encountered on each level.
344 ///
345 /// Used to align "<<" operators. 0 if no such operator has been encountered
346 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000347 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000348
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000349 /// \brief Whether a newline needs to be inserted before the block's closing
350 /// brace.
351 ///
352 /// We only want to insert a newline before the closing brace if there also
353 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000354 bool BreakBeforeClosingBrace;
355
Daniel Jasperca6623b2013-01-28 12:45:14 +0000356 /// \brief The column of a \c ? in a conditional expression;
357 unsigned QuestionColumn;
358
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000359 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
360 /// lines, in this context.
361 bool AvoidBinPacking;
362
363 /// \brief Break after the next comma (or all the commas in this context if
364 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000365 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000366
367 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000368 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000369
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000370 /// \brief The position of the colon in an ObjC method declaration/call.
371 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000372
Daniel Jasper54a86022013-02-15 11:07:25 +0000373 /// \brief Break before third operand in ternary expression.
374 bool BreakBeforeThirdOperand;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000375
Daniel Jasper337816e2013-01-11 10:22:12 +0000376 bool operator<(const ParenState &Other) const {
377 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000378 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000379 if (LastSpace != Other.LastSpace)
380 return LastSpace < Other.LastSpace;
381 if (FirstLessLess != Other.FirstLessLess)
382 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000383 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
384 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000385 if (QuestionColumn != Other.QuestionColumn)
386 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000387 if (AvoidBinPacking != Other.AvoidBinPacking)
388 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000389 if (BreakBeforeParameter != Other.BreakBeforeParameter)
390 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000391 if (HasMultiParameterLine != Other.HasMultiParameterLine)
392 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000393 if (ColonPos != Other.ColonPos)
394 return ColonPos < Other.ColonPos;
Daniel Jasper54a86022013-02-15 11:07:25 +0000395 if (BreakBeforeThirdOperand != Other.BreakBeforeThirdOperand)
396 return BreakBeforeThirdOperand;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000397 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000398 }
399 };
400
401 /// \brief The current state when indenting a unwrapped line.
402 ///
403 /// As the indenting tries different combinations this is copied by value.
404 struct LineState {
405 /// \brief The number of used columns in the current line.
406 unsigned Column;
407
408 /// \brief The token that needs to be next formatted.
409 const AnnotatedToken *NextToken;
410
Daniel Jasperbbc84152013-01-29 11:27:30 +0000411 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000412 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000413 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000414 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000415
416 /// \brief \c true if this line contains a continued for-loop section.
417 bool LineContainsContinuedForLoopSection;
418
Daniel Jasper400adc62013-02-08 15:28:42 +0000419 /// \brief The level of nesting inside (), [], <> and {}.
420 unsigned ParenLevel;
421
Daniel Jasper40c36c52013-02-18 11:05:07 +0000422 /// \brief The \c ParenLevel at the start of this line.
423 unsigned StartOfLineLevel;
424
Manuel Klimek02f640a2013-02-20 15:25:48 +0000425 /// \brief The start column of the string literal, if we're in a string
426 /// literal sequence, 0 otherwise.
427 unsigned StartOfStringLiteral;
428
Daniel Jasper337816e2013-01-11 10:22:12 +0000429 /// \brief A stack keeping track of properties applying to parenthesis
430 /// levels.
431 std::vector<ParenState> Stack;
432
433 /// \brief Comparison operator to be able to used \c LineState in \c map.
434 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000435 if (NextToken != Other.NextToken)
436 return NextToken < Other.NextToken;
437 if (Column != Other.Column)
438 return Column < Other.Column;
439 if (VariablePos != Other.VariablePos)
440 return VariablePos < Other.VariablePos;
441 if (LineContainsContinuedForLoopSection !=
442 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000443 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000444 if (ParenLevel != Other.ParenLevel)
445 return ParenLevel < Other.ParenLevel;
446 if (StartOfLineLevel != Other.StartOfLineLevel)
447 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000448 if (StartOfStringLiteral != Other.StartOfStringLiteral)
449 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000450 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000451 }
452 };
453
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000454 /// \brief Appends the next token to \p State and updates information
455 /// necessary for indentation.
456 ///
457 /// Puts the token on the current line if \p Newline is \c true and adds a
458 /// line break and necessary indentation otherwise.
459 ///
460 /// If \p DryRun is \c false, also creates and stores the required
461 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000462 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000463 const AnnotatedToken &Current = *State.NextToken;
464 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000466
Daniel Jasper4b866272013-02-01 11:00:45 +0000467 if (Current.Type == TT_ImplicitStringLiteral) {
468 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
469 State.NextToken->FormatTok.TokenLength;
470 if (State.NextToken->Children.empty())
471 State.NextToken = NULL;
472 else
473 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000474 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000475 }
476
Daniel Jasperf7935112012-12-03 18:12:45 +0000477 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000478 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000479 if (Current.is(tok::r_brace)) {
480 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000481 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000482 State.StartOfStringLiteral != 0) {
483 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000484 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000485 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000486 State.Stack.back().FirstLessLess != 0) {
487 State.Column = State.Stack.back().FirstLessLess;
488 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000489 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000490 Current.is(tok::period) || Current.is(tok::arrow) ||
491 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000492 // Indent and extra 4 spaces after if we know the current expression is
493 // continued. Don't do that on the top level, as we already indent 4
494 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000495 State.Column = std::max(State.Stack.back().LastSpace,
496 State.Stack.back().Indent) + 4;
497 } else if (Current.Type == TT_ConditionalExpr) {
498 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000499 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000500 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
501 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000502 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000503 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
504 Current.Type == TT_StartOfName) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000505 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000506 } else if (Current.Type == TT_ObjCSelectorName) {
507 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
508 State.Column =
509 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
510 } else {
511 State.Column = State.Stack.back().Indent;
512 State.Stack.back().ColonPos =
513 State.Column + Current.FormatTok.TokenLength;
514 }
515 } else if (Previous.Type == TT_ObjCMethodExpr) {
516 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000517 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000518 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000519 }
520
Daniel Jasper54a86022013-02-15 11:07:25 +0000521 if (Current.is(tok::question))
522 State.Stack.back().BreakBeforeThirdOperand = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000523 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000524 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000525
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000526 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000527 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000528
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000529 if (!DryRun) {
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000530 unsigned NewLines =
531 std::max(1u, std::min(Current.FormatTok.NewlinesBefore,
532 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000533 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000534 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000535 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000536 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000537 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000538 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000539 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000540
Daniel Jasper400adc62013-02-08 15:28:42 +0000541 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000542 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000543 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000544 State.Stack.back().Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000545 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000546 if (Current.is(tok::equal) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000547 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000548 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000549
Daniel Jaspereef30492013-02-11 12:36:37 +0000550 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000551
Daniel Jasperf7935112012-12-03 18:12:45 +0000552 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000553 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000555 if (Current.Type == TT_ObjCSelectorName &&
556 State.Stack.back().ColonPos == 0) {
557 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
558 State.Column + Spaces + Current.FormatTok.TokenLength)
559 State.Stack.back().ColonPos =
560 State.Stack.back().Indent + Current.LongestObjCSelectorName;
561 else
562 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000563 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000564 }
565
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000566 if (Current.Type != TT_LineComment &&
567 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
568 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000569 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000570 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000571 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000572
Daniel Jaspere9de2602012-12-06 09:56:08 +0000573 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000574 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
575 // Treat the condition inside an if as if it was a second function
576 // parameter, i.e. let nested calls have an indent of 4.
577 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000578 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000579 // Top-level spaces are exempt as that mostly leads to better results.
580 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000581 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000582 Previous.Type == TT_ConditionalExpr ||
583 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000584 getPrecedence(Previous) != prec::Assignment)
585 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000586 else if (Previous.Type == TT_InheritanceColon)
587 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000588 else if (Previous.ParameterCount > 1 &&
589 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000590 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000591 Previous.Type == TT_TemplateOpener))
592 // If this function has multiple parameters, indent nested calls from
593 // the start of the first parameter.
594 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000595 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
596 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
597 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000599
600 // If we break after an {, we should also break before the corresponding }.
601 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000602 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000603
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000604 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000605 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jaspere941b162013-01-23 10:08:28 +0000606 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000607 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000608 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
609 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000610 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
611 Line.MustBeDeclaration))
Daniel Jasperacc33662013-02-08 08:22:00 +0000612 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000613
Daniel Jaspere941b162013-01-23 10:08:28 +0000614 // Any break on this level means that the parent level has been broken
615 // and we need to avoid bin packing there.
616 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasperf7f13c02013-02-04 07:30:30 +0000617 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperacc33662013-02-08 08:22:00 +0000618 State.Stack[i].BreakBeforeParameter = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000619 }
620 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000621
Manuel Klimek1998ea22013-02-20 10:15:13 +0000622 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000623 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000624
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000625 /// \brief Mark the next token as consumed in \p State and modify its stacks
626 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000627 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000629 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000630
Daniel Jaspereead02b2013-02-14 08:42:54 +0000631 if (Current.Type == TT_InheritanceColon)
632 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000633 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
634 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000635 if (Current.is(tok::question))
636 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper23e8e0c2013-02-15 16:49:44 +0000637 if (Current.Type == TT_CtorInitializerColon &&
638 Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
639 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000640 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000641 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperacc33662013-02-08 08:22:00 +0000642 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
643 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000644 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000645
Daniel Jasper400adc62013-02-08 15:28:42 +0000646 // Insert scopes created by fake parenthesis.
647 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
648 ParenState NewParenState = State.Stack.back();
649 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
650 State.Stack.push_back(NewParenState);
651 }
652
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000653 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000655 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
656 Current.is(tok::l_brace) ||
657 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000658 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000659 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000660 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000661 NewIndent = 2 + State.Stack.back().LastSpace;
662 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000663 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000664 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000665 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000666 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000667 State.Stack.push_back(
668 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
669 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000670 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000671 }
672
Daniel Jasperacc33662013-02-08 08:22:00 +0000673 // If this '[' opens an ObjC call, determine whether all parameters fit into
674 // one line and put one per line if they don't.
675 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
676 Current.MatchingParen != NULL) {
677 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
678 State.Stack.back().BreakBeforeParameter = true;
679 }
680
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000681 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000682 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000683 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
684 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
685 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000686 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000687 --State.ParenLevel;
688 }
689
690 // Remove scopes created by fake parenthesis.
691 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
692 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000693 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000694
Manuel Klimek0c915712013-02-20 15:32:58 +0000695 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000696 State.StartOfStringLiteral = State.Column;
697 } else if (Current.isNot(tok::comment)) {
698 State.StartOfStringLiteral = 0;
699 }
700
Manuel Klimek1998ea22013-02-20 10:15:13 +0000701 State.Column += Current.FormatTok.TokenLength;
702
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000703 if (State.NextToken->Children.empty())
704 State.NextToken = NULL;
705 else
706 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000707
Manuel Klimek1998ea22013-02-20 10:15:13 +0000708 return breakProtrudingToken(Current, State, DryRun);
709 }
710
711 /// \brief If the current token sticks out over the end of the line, break
712 /// it if possible.
713 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
714 bool DryRun) {
715 if (Current.isNot(tok::string_literal))
716 return 0;
717
718 unsigned Penalty = 0;
719 unsigned TailOffset = 0;
720 unsigned TailLength = Current.FormatTok.TokenLength;
721 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
722 unsigned OffsetFromStart = 0;
723 while (StartColumn + TailLength > getColumnLimit()) {
724 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
725 TailOffset, TailLength);
726 StringRef::size_type SplitPoint =
727 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
728 if (SplitPoint == StringRef::npos)
729 break;
730 assert(SplitPoint != 0);
731 // +2, because 'Text' starts after the opening quotes, and does not
732 // include the closing quote we need to insert.
733 unsigned WhitespaceStartColumn =
734 StartColumn + OffsetFromStart + SplitPoint + 2;
735 State.Stack.back().LastSpace = StartColumn;
736 if (!DryRun) {
737 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
738 Line.InPPDirective, StartColumn,
739 WhitespaceStartColumn, Style);
740 }
741 TailOffset += SplitPoint + 1;
742 TailLength -= SplitPoint + 1;
743 OffsetFromStart = 1;
744 Penalty += 100;
745 }
746 State.Column = StartColumn + TailLength;
747 return Penalty;
748 }
749
750 StringRef::size_type
751 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
752 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
753 return Text.rfind(' ', Offset);
Daniel Jasperf7935112012-12-03 18:12:45 +0000754 }
755
Daniel Jasper2df93312013-01-09 10:16:05 +0000756 unsigned getColumnLimit() {
757 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
758 }
759
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000760 /// \brief An edge in the solution space from \c Previous->State to \c State,
761 /// inserting a newline dependent on the \c NewLine.
762 struct StateNode {
763 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
764 : State(State), NewLine(NewLine), Previous(Previous) {
765 }
766 LineState State;
767 bool NewLine;
768 StateNode *Previous;
769 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000770
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000771 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
772 ///
773 /// In case of equal penalties, we want to prefer states that were inserted
774 /// first. During state generation we make sure that we insert states first
775 /// that break the line as late as possible.
776 typedef std::pair<unsigned, unsigned> OrderedPenalty;
777
778 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
779 /// \c State has the given \c OrderedPenalty.
780 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
781
782 /// \brief The BFS queue type.
783 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
784 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000785
786 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000787 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000788 /// This implements a variant of Dijkstra's algorithm on the graph that spans
789 /// the solution space (\c LineStates are the nodes). The algorithm tries to
790 /// find the shortest path (the one with lowest penalty) from \p InitialState
791 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000792 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000793 std::set<LineState> Seen;
794
Daniel Jasper4b866272013-02-01 11:00:45 +0000795 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000796 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
798 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
799 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000800
801 // While not empty, take first element and follow edges.
802 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000803 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000804 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000805 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000806 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000807 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000808 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000809 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000810
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000811 if (!Seen.insert(Node->State).second)
812 // State already examined with lower penalty.
813 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000814
Manuel Klimekaf491072013-02-13 10:54:19 +0000815 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
816 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000817 }
818
819 if (Queue.empty())
820 // We were unable to find a solution, do nothing.
821 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000822 return 0;
823
Daniel Jasper4b866272013-02-01 11:00:45 +0000824 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000825 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000826 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000827
Daniel Jasper4b866272013-02-01 11:00:45 +0000828 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000829 return Queue.top().second->State.Column;
830 }
831
832 void reconstructPath(LineState &State, StateNode *Current) {
833 // FIXME: This recursive implementation limits the possible number
834 // of tokens per line if compiled into a binary with small stack space.
835 // To become more independent of stack frame limitations we would need
836 // to also change the TokenAnnotator.
837 if (Current->Previous == NULL)
838 return;
839 reconstructPath(State, Current->Previous);
840 DEBUG({
841 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000842 llvm::errs()
843 << "Penalty for splitting before "
844 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
845 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 }
847 });
848 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000849 }
850
Manuel Klimekaf491072013-02-13 10:54:19 +0000851 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000852 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000853 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000854 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000855 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
856 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000857 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000858 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000859 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000860 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000861 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000862 Penalty += PreviousNode->State.NextToken->SplitPenalty;
863
864 StateNode *Node = new (Allocator.Allocate())
865 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000866 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000867 if (Node->State.Column > getColumnLimit()) {
868 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000869 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000870 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000871
872 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
873 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000874 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000875
Daniel Jasper4b866272013-02-01 11:00:45 +0000876 /// \brief Returns \c true, if a line break after \p State is allowed.
877 bool canBreak(const LineState &State) {
878 if (!State.NextToken->CanBreakBefore &&
879 !(State.NextToken->is(tok::r_brace) &&
880 State.Stack.back().BreakBeforeClosingBrace))
881 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000882 // This prevents breaks like:
883 // ...
884 // SomeParameter, OtherParameter).DoSomething(
885 // ...
886 // As they hide "DoSomething" and generally bad for readability.
887 if (State.NextToken->Parent->is(tok::l_paren) &&
888 State.ParenLevel <= State.StartOfLineLevel)
889 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000890 // Trying to insert a parameter on a new line if there are already more than
891 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000892 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000893 State.Stack.back().AvoidBinPacking)
894 return false;
895 return true;
896 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000897
Daniel Jasper4b866272013-02-01 11:00:45 +0000898 /// \brief Returns \c true, if a line break after \p State is mandatory.
899 bool mustBreak(const LineState &State) {
900 if (State.NextToken->MustBreakBefore)
901 return true;
902 if (State.NextToken->is(tok::r_brace) &&
903 State.Stack.back().BreakBeforeClosingBrace)
904 return true;
905 if (State.NextToken->Parent->is(tok::semi) &&
906 State.LineContainsContinuedForLoopSection)
907 return true;
908 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000909 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000910 !isTrailingComment(*State.NextToken) &&
911 State.NextToken->isNot(tok::r_paren))
Daniel Jasper4b866272013-02-01 11:00:45 +0000912 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000913 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
914 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000915 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000916 State.NextToken->LongestObjCSelectorName == 0 &&
917 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000918 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000919 if ((State.NextToken->Type == TT_CtorInitializerColon ||
920 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000921 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000922 return true;
Daniel Jasper54a86022013-02-15 11:07:25 +0000923 if (State.NextToken->is(tok::colon) &&
924 State.Stack.back().BreakBeforeThirdOperand)
925 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000926 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000927 }
928
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 FormatStyle Style;
930 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000931 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000932 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000933 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000934 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000935
936 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
937 QueueType Queue;
938 // Increasing count of \c StateNode items we have created. This is used
939 // to create a deterministic order independent of the container.
940 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000941};
942
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000943class LexerBasedFormatTokenSource : public FormatTokenSource {
944public:
945 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000946 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000947 IdentTable(Lex.getLangOpts()) {
948 Lex.SetKeepWhitespaceMode(true);
949 }
950
951 virtual FormatToken getNextToken() {
952 if (GreaterStashed) {
953 FormatTok.NewlinesBefore = 0;
954 FormatTok.WhiteSpaceStart =
955 FormatTok.Tok.getLocation().getLocWithOffset(1);
956 FormatTok.WhiteSpaceLength = 0;
957 GreaterStashed = false;
958 return FormatTok;
959 }
960
961 FormatTok = FormatToken();
962 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000963 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000964 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000965 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
966 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000967
968 // Consume and record whitespace until we find a significant token.
969 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000970 unsigned Newlines = Text.count('\n');
971 unsigned EscapedNewlines = Text.count("\\\n");
972 FormatTok.NewlinesBefore += Newlines;
973 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000974 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
975
976 if (FormatTok.Tok.is(tok::eof))
977 return FormatTok;
978 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000979 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000980 }
Manuel Klimekef920692013-01-07 07:56:50 +0000981
982 // Now FormatTok is the next non-whitespace token.
983 FormatTok.TokenLength = Text.size();
984
Manuel Klimek1abf7892013-01-04 23:34:14 +0000985 // In case the token starts with escaped newlines, we want to
986 // take them into account as whitespace - this pattern is quite frequent
987 // in macro definitions.
988 // FIXME: What do we want to do with other escaped spaces, and escaped
989 // spaces or newlines in the middle of tokens?
990 // FIXME: Add a more explicit test.
991 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000992 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000993 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000994 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000995 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000996 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000997 }
998
999 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001000 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001001 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001002 FormatTok.Tok.setKind(Info.getTokenID());
1003 }
1004
1005 if (FormatTok.Tok.is(tok::greatergreater)) {
1006 FormatTok.Tok.setKind(tok::greater);
1007 GreaterStashed = true;
1008 }
1009
1010 return FormatTok;
1011 }
1012
Nico Weber29f9dea2013-02-11 15:32:15 +00001013 IdentifierTable &getIdentTable() { return IdentTable; }
1014
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001015private:
1016 FormatToken FormatTok;
1017 bool GreaterStashed;
1018 Lexer &Lex;
1019 SourceManager &SourceMgr;
1020 IdentifierTable IdentTable;
1021
1022 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001023 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001024 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1025 Tok.getLength());
1026 }
1027};
1028
Daniel Jasperf7935112012-12-03 18:12:45 +00001029class Formatter : public UnwrappedLineConsumer {
1030public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001031 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1032 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001033 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001034 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001035 Whitespaces(SourceMgr), Ranges(Ranges) {
1036 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001037
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001038 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001039
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001040 void deriveLocalStyle() {
1041 unsigned CountBoundToVariable = 0;
1042 unsigned CountBoundToType = 0;
1043 bool HasCpp03IncompatibleFormat = false;
1044 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1045 if (AnnotatedLines[i].First.Children.empty())
1046 continue;
1047 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1048 while (!Tok->Children.empty()) {
1049 if (Tok->Type == TT_PointerOrReference) {
1050 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1051 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1052 if (SpacesBefore && !SpacesAfter)
1053 ++CountBoundToVariable;
1054 else if (!SpacesBefore && SpacesAfter)
1055 ++CountBoundToType;
1056 }
1057
Daniel Jasper400adc62013-02-08 15:28:42 +00001058 if (Tok->Type == TT_TemplateCloser &&
1059 Tok->Parent->Type == TT_TemplateCloser &&
1060 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001061 HasCpp03IncompatibleFormat = true;
1062 Tok = &Tok->Children[0];
1063 }
1064 }
1065 if (Style.DerivePointerBinding) {
1066 if (CountBoundToType > CountBoundToVariable)
1067 Style.PointerBindsToType = true;
1068 else if (CountBoundToType < CountBoundToVariable)
1069 Style.PointerBindsToType = false;
1070 }
1071 if (Style.Standard == FormatStyle::LS_Auto) {
1072 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1073 : FormatStyle::LS_Cpp03;
1074 }
1075 }
1076
Daniel Jasperf7935112012-12-03 18:12:45 +00001077 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001078 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001079 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001080 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001081 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001082 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1083 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001084 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001085 Annotator.annotate(AnnotatedLines[i]);
1086 }
1087 deriveLocalStyle();
1088 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1089 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001090 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001091 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001092 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001093 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1094 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001095 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001096 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001097 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001098 while (IndentForLevel.size() <= TheLine.Level)
1099 IndentForLevel.push_back(-1);
1100 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001101 bool WasMoved =
1102 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1103 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001104 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001105 unsigned Indent = LevelIndent;
1106 if (static_cast<int>(Indent) + Offset >= 0)
1107 Indent += Offset;
1108 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1109 StructuralError) {
1110 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1111 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1112 } else {
1113 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1114 PreviousEndOfLineColumn);
1115 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001116 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001117 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001118 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001119 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001120 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001121 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001122 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001123 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001124 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1125 TheLine.First.FormatTok.IsFirst) {
1126 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1127 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1128 unsigned LevelIndent = Indent;
1129 if (static_cast<int>(LevelIndent) - Offset >= 0)
1130 LevelIndent -= Offset;
1131 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001132
1133 // Remove trailing whitespace of the previous line if it was touched.
1134 if (PreviousLineWasTouched)
1135 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1136 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001137 }
Daniel Jasper24570102013-02-14 09:58:41 +00001138 // If we did not reformat this unwrapped line, the column at the end of
1139 // the last token is unchanged - thus, we can calculate the end of the
1140 // last token.
1141 PreviousEndOfLineColumn =
1142 SourceMgr.getSpellingColumnNumber(
1143 TheLine.Last->FormatTok.Tok.getLocation()) +
1144 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1145 SourceMgr, Lex.getLangOpts()) - 1;
1146 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001147 }
1148 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001149 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001150 }
1151
1152private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001153 /// \brief Get the indent of \p Level from \p IndentForLevel.
1154 ///
1155 /// \p IndentForLevel must contain the indent for the level \c l
1156 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1157 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001158 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001159 if (IndentForLevel[Level] != -1)
1160 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001161 if (Level == 0)
1162 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001163 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001164 }
1165
1166 /// \brief Get the offset of the line relatively to the level.
1167 ///
1168 /// For example, 'public:' labels in classes are offset by 1 or 2
1169 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001170 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001171 bool IsAccessModifier = false;
1172 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1173 RootToken.is(tok::kw_private))
1174 IsAccessModifier = true;
1175 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1176 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1177 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1178 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1179 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1180 IsAccessModifier = true;
1181
1182 if (IsAccessModifier)
1183 return Style.AccessModifierOffset;
1184 return 0;
1185 }
1186
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001187 /// \brief Tries to merge lines into one.
1188 ///
1189 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1190 /// if possible; note that \c I will be incremented when lines are merged.
1191 ///
1192 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001193 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001194 std::vector<AnnotatedLine>::iterator &I,
1195 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001196 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1197
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001198 // We can never merge stuff if there are trailing line comments.
1199 if (I->Last->Type == TT_LineComment)
1200 return;
1201
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001202 // Check whether the UnwrappedLine can be put onto a single line. If
1203 // so, this is bound to be the optimal solution (by definition) and we
1204 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001205 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001206 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001207 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001208
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001209 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001210 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001211
Daniel Jasper25837aa2013-01-14 14:14:23 +00001212 if (I->Last->is(tok::l_brace)) {
1213 tryMergeSimpleBlock(I, E, Limit);
1214 } else if (I->First.is(tok::kw_if)) {
1215 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001216 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1217 I->First.FormatTok.IsFirst)) {
1218 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001219 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001220 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001221 }
1222
Daniel Jasper39825ea2013-01-14 15:40:57 +00001223 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1224 std::vector<AnnotatedLine>::iterator E,
1225 unsigned Limit) {
1226 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001227 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1228 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001229 if (I + 2 != E && (I + 2)->InPPDirective &&
1230 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1231 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001232 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001233 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001234 join(Line, *(++I));
1235 }
1236
Daniel Jasper25837aa2013-01-14 14:14:23 +00001237 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1238 std::vector<AnnotatedLine>::iterator E,
1239 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001240 if (!Style.AllowShortIfStatementsOnASingleLine)
1241 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001242 if ((I + 1)->InPPDirective != I->InPPDirective ||
1243 ((I + 1)->InPPDirective &&
1244 (I + 1)->First.FormatTok.HasUnescapedNewline))
1245 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001246 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001247 if (Line.Last->isNot(tok::r_paren))
1248 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001249 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001250 return;
1251 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1252 return;
1253 // Only inline simple if's (no nested if or else).
1254 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1255 return;
1256 join(Line, *(++I));
1257 }
1258
1259 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001260 std::vector<AnnotatedLine>::iterator E,
1261 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001262 // First, check that the current line allows merging. This is the case if
1263 // we're not in a control flow statement and the last token is an opening
1264 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001265 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001266 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1268 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1269 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1270 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001271 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001272 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1273 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001274 if (!AllowedTokens)
1275 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001276
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001277 AnnotatedToken *Tok = &(I + 1)->First;
1278 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1279 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jaspereef30492013-02-11 12:36:37 +00001280 Tok->SpacesRequiredBefore = 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001281 join(Line, *(I + 1));
1282 I += 1;
1283 } else {
1284 // Check that we still have three lines and they fit into the limit.
1285 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1286 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001287 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001288
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001289 // Second, check that the next line does not contain any braces - if it
1290 // does, readability declines when putting it into a single line.
1291 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1292 return;
1293 do {
1294 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1295 return;
1296 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1297 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001298
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001299 // Last, check that the third line contains a single closing brace.
1300 Tok = &(I + 2)->First;
1301 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1302 Tok->MustBreakBefore)
1303 return;
1304
1305 join(Line, *(I + 1));
1306 join(Line, *(I + 2));
1307 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001308 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001309 }
1310
1311 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1312 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001313 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1314 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001315 }
1316
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001317 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1318 A.Last->Children.push_back(B.First);
1319 while (!A.Last->Children.empty()) {
1320 A.Last->Children[0].Parent = A.Last;
1321 A.Last = &A.Last->Children[0];
1322 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001323 }
1324
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001325 bool touchesRanges(const AnnotatedLine &TheLine) {
1326 const FormatToken *First = &TheLine.First.FormatTok;
1327 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001328 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001329 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001330 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001331 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1332 Ranges[i].getBegin()) &&
1333 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1334 LineRange.getBegin()))
1335 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001336 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001337 return false;
1338 }
1339
1340 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001341 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001342 }
1343
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001344 /// \brief Add a new line and the required indent before the first Token
1345 /// of the \c UnwrappedLine if there was no structural parsing error.
1346 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001347 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1348 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001349 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001350
Daniel Jasperbbc84152013-01-29 11:27:30 +00001351 unsigned Newlines =
1352 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001353 if (Newlines == 0 && !Tok.IsFirst)
1354 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001355
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001356 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001357 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001358 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001359 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1360 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001361 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001362 }
1363
Alexander Kornienko116ba682013-01-14 11:34:14 +00001364 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001365 FormatStyle Style;
1366 Lexer &Lex;
1367 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001368 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001369 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001370 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001371 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001372};
1373
Daniel Jasperbbc84152013-01-29 11:27:30 +00001374tooling::Replacements
1375reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1376 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001377 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001378 OwningPtr<DiagnosticConsumer> DiagPrinter;
1379 if (DiagClient == 0) {
1380 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1381 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1382 DiagClient = DiagPrinter.get();
1383 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001384 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001385 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001386 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001387 Diagnostics.setSourceManager(&SourceMgr);
1388 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001389 return formatter.format();
1390}
1391
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001392LangOptions getFormattingLangOpts() {
1393 LangOptions LangOpts;
1394 LangOpts.CPlusPlus = 1;
1395 LangOpts.CPlusPlus11 = 1;
1396 LangOpts.Bool = 1;
1397 LangOpts.ObjC1 = 1;
1398 LangOpts.ObjC2 = 1;
1399 return LangOpts;
1400}
1401
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001402} // namespace format
1403} // namespace clang