blob: 8bc414cd021611ee3b6a7e398958221def59e537 [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),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000269 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000270
Manuel Klimek1abf7892013-01-04 23:34:14 +0000271 /// \brief Formats an \c UnwrappedLine.
272 ///
273 /// \returns The column after the last token in the last line of the
274 /// \c UnwrappedLine.
275 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000276 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000277 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000278 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000279 State.NextToken = &RootToken;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000280 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
281 !Style.BinPackParameters,
282 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000283 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000284 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000285 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000286 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000287 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000288
Manuel Klimek24998102013-01-16 14:55:28 +0000289 DEBUG({
290 DebugTokenState(*State.NextToken);
291 });
292
Daniel Jaspere9de2602012-12-06 09:56:08 +0000293 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000294 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000295
Daniel Jasper4b866272013-02-01 11:00:45 +0000296 // If everything fits on a single line, just put it there.
297 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
298 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000299 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000300 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000301 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000302 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000303
Daniel Jasperacc33662013-02-08 08:22:00 +0000304 // If the ObjC method declaration does not fit on a line, we should format
305 // it with one arg per line.
306 if (Line.Type == LT_ObjCMethodDecl)
307 State.Stack.back().BreakBeforeParameter = true;
308
Daniel Jasper4b866272013-02-01 11:00:45 +0000309 // Find best solution in solution space.
310 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000311 }
312
313private:
Manuel Klimek24998102013-01-16 14:55:28 +0000314 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
315 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000316 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
317 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000318 llvm::errs();
319 }
320
Daniel Jasper337816e2013-01-11 10:22:12 +0000321 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000322 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
323 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000324 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
325 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000326 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000327 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000328
Daniel Jasperf7935112012-12-03 18:12:45 +0000329 /// \brief The position to which a specific parenthesis level needs to be
330 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000331 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000332
Daniel Jaspere9de2602012-12-06 09:56:08 +0000333 /// \brief The position of the last space on each level.
334 ///
335 /// Used e.g. to break like:
336 /// functionCall(Parameter, otherCall(
337 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000338 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000339
Daniel Jaspere9de2602012-12-06 09:56:08 +0000340 /// \brief The position the first "<<" operator encountered on each level.
341 ///
342 /// Used to align "<<" operators. 0 if no such operator has been encountered
343 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000344 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000345
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000346 /// \brief Whether a newline needs to be inserted before the block's closing
347 /// brace.
348 ///
349 /// We only want to insert a newline before the closing brace if there also
350 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000351 bool BreakBeforeClosingBrace;
352
Daniel Jasperca6623b2013-01-28 12:45:14 +0000353 /// \brief The column of a \c ? in a conditional expression;
354 unsigned QuestionColumn;
355
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000356 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
357 /// lines, in this context.
358 bool AvoidBinPacking;
359
360 /// \brief Break after the next comma (or all the commas in this context if
361 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000362 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000363
364 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000365 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000366
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000367 /// \brief The position of the colon in an ObjC method declaration/call.
368 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000369
Daniel Jasper337816e2013-01-11 10:22:12 +0000370 bool operator<(const ParenState &Other) const {
371 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000372 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000373 if (LastSpace != Other.LastSpace)
374 return LastSpace < Other.LastSpace;
375 if (FirstLessLess != Other.FirstLessLess)
376 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000377 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
378 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000379 if (QuestionColumn != Other.QuestionColumn)
380 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000381 if (AvoidBinPacking != Other.AvoidBinPacking)
382 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000383 if (BreakBeforeParameter != Other.BreakBeforeParameter)
384 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000385 if (HasMultiParameterLine != Other.HasMultiParameterLine)
386 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000387 if (ColonPos != Other.ColonPos)
388 return ColonPos < Other.ColonPos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000389 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000390 }
391 };
392
393 /// \brief The current state when indenting a unwrapped line.
394 ///
395 /// As the indenting tries different combinations this is copied by value.
396 struct LineState {
397 /// \brief The number of used columns in the current line.
398 unsigned Column;
399
400 /// \brief The token that needs to be next formatted.
401 const AnnotatedToken *NextToken;
402
Daniel Jasperbbc84152013-01-29 11:27:30 +0000403 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000404 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000405 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000406 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000407
408 /// \brief \c true if this line contains a continued for-loop section.
409 bool LineContainsContinuedForLoopSection;
410
Daniel Jasper400adc62013-02-08 15:28:42 +0000411 /// \brief The level of nesting inside (), [], <> and {}.
412 unsigned ParenLevel;
413
Daniel Jasper40c36c52013-02-18 11:05:07 +0000414 /// \brief The \c ParenLevel at the start of this line.
415 unsigned StartOfLineLevel;
416
Manuel Klimek02f640a2013-02-20 15:25:48 +0000417 /// \brief The start column of the string literal, if we're in a string
418 /// literal sequence, 0 otherwise.
419 unsigned StartOfStringLiteral;
420
Daniel Jasper337816e2013-01-11 10:22:12 +0000421 /// \brief A stack keeping track of properties applying to parenthesis
422 /// levels.
423 std::vector<ParenState> Stack;
424
425 /// \brief Comparison operator to be able to used \c LineState in \c map.
426 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000427 if (NextToken != Other.NextToken)
428 return NextToken < Other.NextToken;
429 if (Column != Other.Column)
430 return Column < Other.Column;
431 if (VariablePos != Other.VariablePos)
432 return VariablePos < Other.VariablePos;
433 if (LineContainsContinuedForLoopSection !=
434 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000435 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000436 if (ParenLevel != Other.ParenLevel)
437 return ParenLevel < Other.ParenLevel;
438 if (StartOfLineLevel != Other.StartOfLineLevel)
439 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000440 if (StartOfStringLiteral != Other.StartOfStringLiteral)
441 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000442 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000443 }
444 };
445
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000446 /// \brief Appends the next token to \p State and updates information
447 /// necessary for indentation.
448 ///
449 /// Puts the token on the current line if \p Newline is \c true and adds a
450 /// line break and necessary indentation otherwise.
451 ///
452 /// If \p DryRun is \c false, also creates and stores the required
453 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000454 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000455 const AnnotatedToken &Current = *State.NextToken;
456 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000457 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000458
Daniel Jasper4b866272013-02-01 11:00:45 +0000459 if (Current.Type == TT_ImplicitStringLiteral) {
460 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
461 State.NextToken->FormatTok.TokenLength;
462 if (State.NextToken->Children.empty())
463 State.NextToken = NULL;
464 else
465 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000466 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000467 }
468
Daniel Jasperf7935112012-12-03 18:12:45 +0000469 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000470 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000471 if (Current.is(tok::r_brace)) {
472 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000473 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000474 State.StartOfStringLiteral != 0) {
475 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000476 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000477 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000478 State.Stack.back().FirstLessLess != 0) {
479 State.Column = State.Stack.back().FirstLessLess;
480 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000481 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000482 Current.is(tok::period) || Current.is(tok::arrow) ||
483 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000484 // Indent and extra 4 spaces after if we know the current expression is
485 // continued. Don't do that on the top level, as we already indent 4
486 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000487 State.Column = std::max(State.Stack.back().LastSpace,
488 State.Stack.back().Indent) + 4;
489 } else if (Current.Type == TT_ConditionalExpr) {
490 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000491 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000492 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
493 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000494 State.Column = State.VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000495 } else if (Previous.ClosesTemplateDeclaration ||
496 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000497 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000498 } else if (Current.Type == TT_ObjCSelectorName) {
499 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
500 State.Column =
501 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
502 } else {
503 State.Column = State.Stack.back().Indent;
504 State.Stack.back().ColonPos =
505 State.Column + Current.FormatTok.TokenLength;
506 }
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000507 } else if (Previous.Type == TT_ObjCMethodExpr ||
508 Current.Type == TT_StartOfName) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000509 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000510 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000511 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000512 }
513
Daniel Jasper54a86022013-02-15 11:07:25 +0000514 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000515 State.Stack.back().BreakBeforeParameter = true;
516 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
517 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000518 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000519
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000520 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000521 unsigned NewLines = 1;
522 if (Current.Type == TT_LineComment)
523 NewLines =
524 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
525 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000526 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000527 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000528 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000529 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000530 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000531 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000532 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000533
Daniel Jasper400adc62013-02-08 15:28:42 +0000534 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000535 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000536 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000537 State.Stack.back().Indent += 2;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000538
539 // Any break on this level means that the parent level has been broken
540 // and we need to avoid bin packing there.
541 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
542 State.Stack[i].BreakBeforeParameter = true;
543 }
544 // If we break after {, we should also break before the corresponding }.
545 if (Previous.is(tok::l_brace))
546 State.Stack.back().BreakBeforeClosingBrace = true;
547
548 if (State.Stack.back().AvoidBinPacking) {
549 // If we are breaking after '(', '{', '<', this is not bin packing
550 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000551 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000552 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
553 Line.MustBeDeclaration))
554 State.Stack.back().BreakBeforeParameter = true;
555 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000556 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000557 // FIXME: Put VariablePos into ParenState and remove second part of if().
558 if (Current.is(tok::equal) &&
559 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000560 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000561
Daniel Jaspereef30492013-02-11 12:36:37 +0000562 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000563
Daniel Jasperf7935112012-12-03 18:12:45 +0000564 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000565 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000566
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000567 if (Current.Type == TT_ObjCSelectorName &&
568 State.Stack.back().ColonPos == 0) {
569 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
570 State.Column + Spaces + Current.FormatTok.TokenLength)
571 State.Stack.back().ColonPos =
572 State.Stack.back().Indent + Current.LongestObjCSelectorName;
573 else
574 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000575 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000576 }
577
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000578 if (Current.Type != TT_LineComment &&
579 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
580 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000581 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000582 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000583 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000584
Daniel Jaspere9de2602012-12-06 09:56:08 +0000585 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000586 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
587 // Treat the condition inside an if as if it was a second function
588 // parameter, i.e. let nested calls have an indent of 4.
589 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000590 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000591 // Top-level spaces are exempt as that mostly leads to better results.
592 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000593 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000594 Previous.Type == TT_ConditionalExpr ||
595 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000596 getPrecedence(Previous) != prec::Assignment)
597 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000598 else if (Previous.Type == TT_InheritanceColon)
599 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000600 else if (Previous.ParameterCount > 1 &&
601 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000602 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000603 Previous.Type == TT_TemplateOpener))
604 // If this function has multiple parameters, indent nested calls from
605 // the start of the first parameter.
606 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000607 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
608 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
609 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000610 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000611
Manuel Klimek1998ea22013-02-20 10:15:13 +0000612 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000614
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000615 /// \brief Mark the next token as consumed in \p State and modify its stacks
616 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000617 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000618 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000619 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000620
Daniel Jaspereead02b2013-02-14 08:42:54 +0000621 if (Current.Type == TT_InheritanceColon)
622 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000623 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
624 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000625 if (Current.is(tok::question))
626 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000627 if (Current.Type == TT_CtorInitializerColon) {
628 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
629 State.Stack.back().AvoidBinPacking = true;
630 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000631 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000632
Daniel Jasper400adc62013-02-08 15:28:42 +0000633 // Insert scopes created by fake parenthesis.
634 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
635 ParenState NewParenState = State.Stack.back();
636 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000637 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000638 State.Stack.push_back(NewParenState);
639 }
640
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000641 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000642 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000643 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
644 Current.is(tok::l_brace) ||
645 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000646 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000647 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000648 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000649 NewIndent = 2 + State.Stack.back().LastSpace;
650 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000651 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000652 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000653 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000654 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000655 State.Stack.push_back(
656 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
657 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000658 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000659 }
660
Daniel Jasperacc33662013-02-08 08:22:00 +0000661 // If this '[' opens an ObjC call, determine whether all parameters fit into
662 // one line and put one per line if they don't.
663 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
664 Current.MatchingParen != NULL) {
665 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
666 State.Stack.back().BreakBeforeParameter = true;
667 }
668
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000669 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000670 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000671 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
672 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
673 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000674 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000675 --State.ParenLevel;
676 }
677
678 // Remove scopes created by fake parenthesis.
679 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
680 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000682
Manuel Klimek0c915712013-02-20 15:32:58 +0000683 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000684 State.StartOfStringLiteral = State.Column;
685 } else if (Current.isNot(tok::comment)) {
686 State.StartOfStringLiteral = 0;
687 }
688
Manuel Klimek1998ea22013-02-20 10:15:13 +0000689 State.Column += Current.FormatTok.TokenLength;
690
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000691 if (State.NextToken->Children.empty())
692 State.NextToken = NULL;
693 else
694 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000695
Manuel Klimek1998ea22013-02-20 10:15:13 +0000696 return breakProtrudingToken(Current, State, DryRun);
697 }
698
699 /// \brief If the current token sticks out over the end of the line, break
700 /// it if possible.
701 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
702 bool DryRun) {
703 if (Current.isNot(tok::string_literal))
704 return 0;
705
706 unsigned Penalty = 0;
707 unsigned TailOffset = 0;
708 unsigned TailLength = Current.FormatTok.TokenLength;
709 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
710 unsigned OffsetFromStart = 0;
711 while (StartColumn + TailLength > getColumnLimit()) {
712 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
713 TailOffset, TailLength);
714 StringRef::size_type SplitPoint =
715 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
716 if (SplitPoint == StringRef::npos)
717 break;
718 assert(SplitPoint != 0);
719 // +2, because 'Text' starts after the opening quotes, and does not
720 // include the closing quote we need to insert.
721 unsigned WhitespaceStartColumn =
722 StartColumn + OffsetFromStart + SplitPoint + 2;
723 State.Stack.back().LastSpace = StartColumn;
724 if (!DryRun) {
725 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
726 Line.InPPDirective, StartColumn,
727 WhitespaceStartColumn, Style);
728 }
729 TailOffset += SplitPoint + 1;
730 TailLength -= SplitPoint + 1;
731 OffsetFromStart = 1;
Daniel Jasper5497fce2013-02-26 12:52:34 +0000732 Penalty += Style.PenaltyExcessCharacter;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000733 }
734 State.Column = StartColumn + TailLength;
735 return Penalty;
736 }
737
738 StringRef::size_type
739 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
740 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
741 return Text.rfind(' ', Offset);
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 }
743
Daniel Jasper2df93312013-01-09 10:16:05 +0000744 unsigned getColumnLimit() {
745 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
746 }
747
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000748 /// \brief An edge in the solution space from \c Previous->State to \c State,
749 /// inserting a newline dependent on the \c NewLine.
750 struct StateNode {
751 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000752 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000753 LineState State;
754 bool NewLine;
755 StateNode *Previous;
756 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000757
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000758 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
759 ///
760 /// In case of equal penalties, we want to prefer states that were inserted
761 /// first. During state generation we make sure that we insert states first
762 /// that break the line as late as possible.
763 typedef std::pair<unsigned, unsigned> OrderedPenalty;
764
765 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
766 /// \c State has the given \c OrderedPenalty.
767 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
768
769 /// \brief The BFS queue type.
770 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
771 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000772
773 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000775 /// This implements a variant of Dijkstra's algorithm on the graph that spans
776 /// the solution space (\c LineStates are the nodes). The algorithm tries to
777 /// find the shortest path (the one with lowest penalty) from \p InitialState
778 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000779 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000780 std::set<LineState> Seen;
781
Daniel Jasper4b866272013-02-01 11:00:45 +0000782 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000783 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000784 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
785 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
786 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000787
788 // While not empty, take first element and follow edges.
789 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000790 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000791 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000792 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000793 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000794 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000795 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000796 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000797
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000798 if (!Seen.insert(Node->State).second)
799 // State already examined with lower penalty.
800 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000801
Manuel Klimekaf491072013-02-13 10:54:19 +0000802 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
803 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000804 }
805
806 if (Queue.empty())
807 // We were unable to find a solution, do nothing.
808 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000809 return 0;
810
Daniel Jasper4b866272013-02-01 11:00:45 +0000811 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000812 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000813 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000814
Daniel Jasper4b866272013-02-01 11:00:45 +0000815 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000816 return Queue.top().second->State.Column;
817 }
818
819 void reconstructPath(LineState &State, StateNode *Current) {
820 // FIXME: This recursive implementation limits the possible number
821 // of tokens per line if compiled into a binary with small stack space.
822 // To become more independent of stack frame limitations we would need
823 // to also change the TokenAnnotator.
824 if (Current->Previous == NULL)
825 return;
826 reconstructPath(State, Current->Previous);
827 DEBUG({
828 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000829 llvm::errs()
830 << "Penalty for splitting before "
831 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
832 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000833 }
834 });
835 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000836 }
837
Manuel Klimekaf491072013-02-13 10:54:19 +0000838 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000839 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000840 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000841 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000842 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
843 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000844 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000845 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000847 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000848 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000849 Penalty += PreviousNode->State.NextToken->SplitPenalty;
850
851 StateNode *Node = new (Allocator.Allocate())
852 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000853 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000854 if (Node->State.Column > getColumnLimit()) {
855 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000856 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000857 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000858
859 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
860 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000861 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000862
Daniel Jasper4b866272013-02-01 11:00:45 +0000863 /// \brief Returns \c true, if a line break after \p State is allowed.
864 bool canBreak(const LineState &State) {
865 if (!State.NextToken->CanBreakBefore &&
866 !(State.NextToken->is(tok::r_brace) &&
867 State.Stack.back().BreakBeforeClosingBrace))
868 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000869 // This prevents breaks like:
870 // ...
871 // SomeParameter, OtherParameter).DoSomething(
872 // ...
873 // As they hide "DoSomething" and generally bad for readability.
874 if (State.NextToken->Parent->is(tok::l_paren) &&
875 State.ParenLevel <= State.StartOfLineLevel)
876 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000877 // Trying to insert a parameter on a new line if there are already more than
878 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000879 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000880 State.Stack.back().AvoidBinPacking)
881 return false;
882 return true;
883 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000884
Daniel Jasper4b866272013-02-01 11:00:45 +0000885 /// \brief Returns \c true, if a line break after \p State is mandatory.
886 bool mustBreak(const LineState &State) {
887 if (State.NextToken->MustBreakBefore)
888 return true;
889 if (State.NextToken->is(tok::r_brace) &&
890 State.Stack.back().BreakBeforeClosingBrace)
891 return true;
892 if (State.NextToken->Parent->is(tok::semi) &&
893 State.LineContainsContinuedForLoopSection)
894 return true;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000895 if ((State.NextToken->Parent->is(tok::comma) ||
896 State.NextToken->Parent->is(tok::semi) ||
897 State.NextToken->is(tok::question) ||
898 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000899 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000900 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000901 State.NextToken->isNot(tok::r_paren) &&
902 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000903 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000904 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
905 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000906 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000907 State.NextToken->LongestObjCSelectorName == 0 &&
908 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000909 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000910 if ((State.NextToken->Type == TT_CtorInitializerColon ||
911 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000912 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000913 return true;
914 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 }
916
Daniel Jasperf7935112012-12-03 18:12:45 +0000917 FormatStyle Style;
918 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000919 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000920 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000921 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000922 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000923
924 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
925 QueueType Queue;
926 // Increasing count of \c StateNode items we have created. This is used
927 // to create a deterministic order independent of the container.
928 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000929};
930
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000931class LexerBasedFormatTokenSource : public FormatTokenSource {
932public:
933 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000934 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000935 IdentTable(Lex.getLangOpts()) {
936 Lex.SetKeepWhitespaceMode(true);
937 }
938
939 virtual FormatToken getNextToken() {
940 if (GreaterStashed) {
941 FormatTok.NewlinesBefore = 0;
942 FormatTok.WhiteSpaceStart =
943 FormatTok.Tok.getLocation().getLocWithOffset(1);
944 FormatTok.WhiteSpaceLength = 0;
945 GreaterStashed = false;
946 return FormatTok;
947 }
948
949 FormatTok = FormatToken();
950 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000951 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000952 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000953 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
954 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000955
956 // Consume and record whitespace until we find a significant token.
957 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000958 unsigned Newlines = Text.count('\n');
959 unsigned EscapedNewlines = Text.count("\\\n");
960 FormatTok.NewlinesBefore += Newlines;
961 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000962 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
963
964 if (FormatTok.Tok.is(tok::eof))
965 return FormatTok;
966 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000967 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000968 }
Manuel Klimekef920692013-01-07 07:56:50 +0000969
970 // Now FormatTok is the next non-whitespace token.
971 FormatTok.TokenLength = Text.size();
972
Manuel Klimek1abf7892013-01-04 23:34:14 +0000973 // In case the token starts with escaped newlines, we want to
974 // take them into account as whitespace - this pattern is quite frequent
975 // in macro definitions.
976 // FIXME: What do we want to do with other escaped spaces, and escaped
977 // spaces or newlines in the middle of tokens?
978 // FIXME: Add a more explicit test.
979 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000980 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000981 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000982 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000983 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000984 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000985 }
986
987 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000988 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000989 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000990 FormatTok.Tok.setKind(Info.getTokenID());
991 }
992
993 if (FormatTok.Tok.is(tok::greatergreater)) {
994 FormatTok.Tok.setKind(tok::greater);
995 GreaterStashed = true;
996 }
997
998 return FormatTok;
999 }
1000
Nico Weber29f9dea2013-02-11 15:32:15 +00001001 IdentifierTable &getIdentTable() { return IdentTable; }
1002
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001003private:
1004 FormatToken FormatTok;
1005 bool GreaterStashed;
1006 Lexer &Lex;
1007 SourceManager &SourceMgr;
1008 IdentifierTable IdentTable;
1009
1010 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001011 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001012 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1013 Tok.getLength());
1014 }
1015};
1016
Daniel Jasperf7935112012-12-03 18:12:45 +00001017class Formatter : public UnwrappedLineConsumer {
1018public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001019 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1020 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001021 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001022 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001023 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001024
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001025 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001026
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001027 void deriveLocalStyle() {
1028 unsigned CountBoundToVariable = 0;
1029 unsigned CountBoundToType = 0;
1030 bool HasCpp03IncompatibleFormat = false;
1031 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1032 if (AnnotatedLines[i].First.Children.empty())
1033 continue;
1034 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1035 while (!Tok->Children.empty()) {
1036 if (Tok->Type == TT_PointerOrReference) {
1037 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1038 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1039 if (SpacesBefore && !SpacesAfter)
1040 ++CountBoundToVariable;
1041 else if (!SpacesBefore && SpacesAfter)
1042 ++CountBoundToType;
1043 }
1044
Daniel Jasper400adc62013-02-08 15:28:42 +00001045 if (Tok->Type == TT_TemplateCloser &&
1046 Tok->Parent->Type == TT_TemplateCloser &&
1047 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001048 HasCpp03IncompatibleFormat = true;
1049 Tok = &Tok->Children[0];
1050 }
1051 }
1052 if (Style.DerivePointerBinding) {
1053 if (CountBoundToType > CountBoundToVariable)
1054 Style.PointerBindsToType = true;
1055 else if (CountBoundToType < CountBoundToVariable)
1056 Style.PointerBindsToType = false;
1057 }
1058 if (Style.Standard == FormatStyle::LS_Auto) {
1059 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1060 : FormatStyle::LS_Cpp03;
1061 }
1062 }
1063
Daniel Jasperf7935112012-12-03 18:12:45 +00001064 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001065 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001066 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001067 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001068 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001069 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1070 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001071 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001072 Annotator.annotate(AnnotatedLines[i]);
1073 }
1074 deriveLocalStyle();
1075 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1076 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001077 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001078 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001079 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001080 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1081 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001082 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001083 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001084 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001085 while (IndentForLevel.size() <= TheLine.Level)
1086 IndentForLevel.push_back(-1);
1087 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001088 bool WasMoved =
1089 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1090 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001091 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001092 unsigned Indent = LevelIndent;
1093 if (static_cast<int>(Indent) + Offset >= 0)
1094 Indent += Offset;
1095 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1096 StructuralError) {
1097 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1098 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1099 } else {
1100 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1101 PreviousEndOfLineColumn);
1102 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001103 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001104 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001105 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001106 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001107 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001108 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001109 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001110 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001111 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1112 TheLine.First.FormatTok.IsFirst) {
1113 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1114 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1115 unsigned LevelIndent = Indent;
1116 if (static_cast<int>(LevelIndent) - Offset >= 0)
1117 LevelIndent -= Offset;
1118 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001119
1120 // Remove trailing whitespace of the previous line if it was touched.
1121 if (PreviousLineWasTouched)
1122 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1123 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001124 }
Daniel Jasper24570102013-02-14 09:58:41 +00001125 // If we did not reformat this unwrapped line, the column at the end of
1126 // the last token is unchanged - thus, we can calculate the end of the
1127 // last token.
1128 PreviousEndOfLineColumn =
1129 SourceMgr.getSpellingColumnNumber(
1130 TheLine.Last->FormatTok.Tok.getLocation()) +
1131 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1132 SourceMgr, Lex.getLangOpts()) - 1;
1133 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001134 }
1135 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001136 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 }
1138
1139private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001140 /// \brief Get the indent of \p Level from \p IndentForLevel.
1141 ///
1142 /// \p IndentForLevel must contain the indent for the level \c l
1143 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1144 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001145 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001146 if (IndentForLevel[Level] != -1)
1147 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001148 if (Level == 0)
1149 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001150 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001151 }
1152
1153 /// \brief Get the offset of the line relatively to the level.
1154 ///
1155 /// For example, 'public:' labels in classes are offset by 1 or 2
1156 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001157 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001158 bool IsAccessModifier = false;
1159 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1160 RootToken.is(tok::kw_private))
1161 IsAccessModifier = true;
1162 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1163 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1164 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1165 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1166 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1167 IsAccessModifier = true;
1168
1169 if (IsAccessModifier)
1170 return Style.AccessModifierOffset;
1171 return 0;
1172 }
1173
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001174 /// \brief Tries to merge lines into one.
1175 ///
1176 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1177 /// if possible; note that \c I will be incremented when lines are merged.
1178 ///
1179 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001180 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001181 std::vector<AnnotatedLine>::iterator &I,
1182 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001183 // We can never merge stuff if there are trailing line comments.
1184 if (I->Last->Type == TT_LineComment)
1185 return;
1186
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001187 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1188 // If we already exceed the column limit, we set 'Limit' to 0. The different
1189 // tryMerge..() functions can then decide whether to still do merging.
1190 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001191
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001192 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001193 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001194
Daniel Jasper25837aa2013-01-14 14:14:23 +00001195 if (I->Last->is(tok::l_brace)) {
1196 tryMergeSimpleBlock(I, E, Limit);
1197 } else if (I->First.is(tok::kw_if)) {
1198 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001199 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1200 I->First.FormatTok.IsFirst)) {
1201 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001202 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001203 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001204 }
1205
Daniel Jasper39825ea2013-01-14 15:40:57 +00001206 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1207 std::vector<AnnotatedLine>::iterator E,
1208 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001209 if (Limit == 0)
1210 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001211 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001212 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1213 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001214 if (I + 2 != E && (I + 2)->InPPDirective &&
1215 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1216 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001217 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001218 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001219 join(Line, *(++I));
1220 }
1221
Daniel Jasper25837aa2013-01-14 14:14:23 +00001222 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1223 std::vector<AnnotatedLine>::iterator E,
1224 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001225 if (Limit == 0)
1226 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001227 if (!Style.AllowShortIfStatementsOnASingleLine)
1228 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001229 if ((I + 1)->InPPDirective != I->InPPDirective ||
1230 ((I + 1)->InPPDirective &&
1231 (I + 1)->First.FormatTok.HasUnescapedNewline))
1232 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001233 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001234 if (Line.Last->isNot(tok::r_paren))
1235 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001236 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001237 return;
1238 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1239 return;
1240 // Only inline simple if's (no nested if or else).
1241 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1242 return;
1243 join(Line, *(++I));
1244 }
1245
1246 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001247 std::vector<AnnotatedLine>::iterator E,
1248 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001249 // First, check that the current line allows merging. This is the case if
1250 // we're not in a control flow statement and the last token is an opening
1251 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001252 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001253 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001254 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1255 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1256 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1257 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001258 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001259 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1260 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001261 if (!AllowedTokens)
1262 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001263
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001264 AnnotatedToken *Tok = &(I + 1)->First;
1265 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001266 !Tok->MustBreakBefore) {
1267 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001268 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001269 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001270 join(Line, *(I + 1));
1271 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001272 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001273 // Check that we still have three lines and they fit into the limit.
1274 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1275 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001276 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001277
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001278 // Second, check that the next line does not contain any braces - if it
1279 // does, readability declines when putting it into a single line.
1280 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1281 return;
1282 do {
1283 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1284 return;
1285 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1286 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001287
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001288 // Last, check that the third line contains a single closing brace.
1289 Tok = &(I + 2)->First;
1290 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1291 Tok->MustBreakBefore)
1292 return;
1293
1294 join(Line, *(I + 1));
1295 join(Line, *(I + 2));
1296 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001297 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001298 }
1299
1300 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1301 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001302 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1303 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001304 }
1305
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001306 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001307 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001308 A.Last->Children.push_back(B.First);
1309 while (!A.Last->Children.empty()) {
1310 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001311 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001312 A.Last = &A.Last->Children[0];
1313 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001314 }
1315
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001316 bool touchesRanges(const AnnotatedLine &TheLine) {
1317 const FormatToken *First = &TheLine.First.FormatTok;
1318 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001319 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001320 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001321 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001322 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1323 Ranges[i].getBegin()) &&
1324 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1325 LineRange.getBegin()))
1326 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001327 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001328 return false;
1329 }
1330
1331 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001332 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001333 }
1334
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001335 /// \brief Add a new line and the required indent before the first Token
1336 /// of the \c UnwrappedLine if there was no structural parsing error.
1337 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001338 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1339 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001340 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001341
Daniel Jasperbbc84152013-01-29 11:27:30 +00001342 unsigned Newlines =
1343 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001344 if (Newlines == 0 && !Tok.IsFirst)
1345 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001346
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001347 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001348 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001349 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001350 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1351 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001352 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001353 }
1354
Alexander Kornienko116ba682013-01-14 11:34:14 +00001355 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001356 FormatStyle Style;
1357 Lexer &Lex;
1358 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001359 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001360 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001361 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001362 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001363};
1364
Daniel Jasperbbc84152013-01-29 11:27:30 +00001365tooling::Replacements
1366reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1367 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001368 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001369 OwningPtr<DiagnosticConsumer> DiagPrinter;
1370 if (DiagClient == 0) {
1371 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1372 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1373 DiagClient = DiagPrinter.get();
1374 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001375 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001376 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001377 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001378 Diagnostics.setSourceManager(&SourceMgr);
1379 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001380 return formatter.format();
1381}
1382
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001383LangOptions getFormattingLangOpts() {
1384 LangOptions LangOpts;
1385 LangOpts.CPlusPlus = 1;
1386 LangOpts.CPlusPlus11 = 1;
1387 LangOpts.Bool = 1;
1388 LangOpts.ObjC1 = 1;
1389 LangOpts.ObjC2 = 1;
1390 return LangOpts;
1391}
1392
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001393} // namespace format
1394} // namespace clang