blob: d8784c126e61f0d516af9d5d20b6431b9b034935 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperf7935112012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperf7935112012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +000064 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperb9caeac2013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperf7935112012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper1b750ed2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000077 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
78 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000079 return ChromiumStyle;
80}
81
Daniel Jasper94f0e132013-02-06 20:07:35 +000082static bool isTrailingComment(const AnnotatedToken &Tok) {
83 return Tok.is(tok::comment) &&
84 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
85}
86
Daniel Jasperacc33662013-02-08 08:22:00 +000087// Returns the length of everything up to the first possible line break after
88// the ), ], } or > matching \c Tok.
89static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
90 if (Tok.MatchingParen == NULL)
91 return 0;
92 AnnotatedToken *End = Tok.MatchingParen;
93 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
94 End = &End->Children[0];
95 }
96 return End->TotalLength - Tok.TotalLength + 1;
97}
98
Daniel Jasperaa701fa2013-01-18 08:44:07 +000099/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000100///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000101/// This includes special handling for certain constructs, e.g. the alignment of
102/// trailing line comments.
103class WhitespaceManager {
104public:
105 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
106
107 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
108 /// each \c AnnotatedToken.
109 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
110 unsigned Spaces, unsigned WhitespaceStartColumn,
111 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000112 // 2+ newlines mean an empty line separating logic scopes.
113 if (NewLines >= 2)
114 alignComments();
115
116 // Align line comments if they are trailing or if they continue other
117 // trailing comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000118 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000119 if (Style.ColumnLimit >=
120 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
121 Comments.push_back(StoredComment());
122 Comments.back().Tok = Tok.FormatTok;
123 Comments.back().Spaces = Spaces;
124 Comments.back().NewLines = NewLines;
Daniel Jasperf79f9352013-02-06 22:04:05 +0000125 if (NewLines == 0)
126 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
127 else
128 Comments.back().MinColumn = Spaces;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000129 Comments.back().MaxColumn =
Daniel Jasper525264c2013-02-13 19:25:54 +0000130 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 return;
132 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000134
135 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper94f0e132013-02-06 20:07:35 +0000136 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper304a9862013-01-21 22:49:20 +0000137 alignComments();
Manuel Klimek1998ea22013-02-20 10:15:13 +0000138 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000139 }
140
141 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
142 /// backslashes to escape newlines inside a preprocessor directive.
143 ///
144 /// This function and \c replaceWhitespace have the same behavior if
145 /// \c Newlines == 0.
146 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
147 unsigned Spaces, unsigned WhitespaceStartColumn,
148 const FormatStyle &Style) {
Manuel Klimek1998ea22013-02-20 10:15:13 +0000149 storeReplacement(
150 Tok.FormatTok,
151 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
152 }
153
154 /// \brief Inserts a line break into the middle of a token.
155 ///
156 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
157 /// break and \p Postfix before the rest of the token starts in the next line.
158 ///
159 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
160 /// used to generate the correct line break.
161 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
162 StringRef Postfix, bool InPPDirective, unsigned Spaces,
163 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
164 std::string NewLineText;
165 if (!InPPDirective)
166 NewLineText = getNewLineText(1, Spaces);
167 else
168 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
169 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
170 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
171 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
172 Replaces.insert(
173 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
174 }
175
176 /// \brief Returns all the \c Replacements created during formatting.
177 const tooling::Replacements &generateReplacements() {
178 alignComments();
179 return Replaces;
180 }
181
182private:
183 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
184 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
185 }
186
187 std::string
188 getNewLineText(unsigned NewLines, unsigned Spaces,
189 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000190 std::string NewLineText;
191 if (NewLines > 0) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000192 unsigned Offset =
193 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000194 for (unsigned i = 0; i < NewLines; ++i) {
195 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
196 NewLineText += "\\\n";
197 Offset = 0;
198 }
199 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000200 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000201 }
202
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000203 /// \brief Structure to store a comment for later layout and alignment.
204 struct StoredComment {
205 FormatToken Tok;
206 unsigned MinColumn;
207 unsigned MaxColumn;
208 unsigned NewLines;
209 unsigned Spaces;
210 };
211 SmallVector<StoredComment, 16> Comments;
212 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
213
214 /// \brief Try to align all stashed comments.
215 void alignComments() {
216 unsigned MinColumn = 0;
217 unsigned MaxColumn = UINT_MAX;
218 comment_iterator Start = Comments.begin();
219 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
220 ++I) {
221 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
222 alignComments(Start, I, MinColumn);
223 MinColumn = I->MinColumn;
224 MaxColumn = I->MaxColumn;
225 Start = I;
226 } else {
227 MinColumn = std::max(MinColumn, I->MinColumn);
228 MaxColumn = std::min(MaxColumn, I->MaxColumn);
229 }
230 }
231 alignComments(Start, Comments.end(), MinColumn);
232 Comments.clear();
233 }
234
235 /// \brief Put all the comments between \p I and \p E into \p Column.
236 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
237 while (I != E) {
238 unsigned Spaces = I->Spaces + Column - I->MinColumn;
239 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper400adc62013-02-08 15:28:42 +0000240 std::string(Spaces, ' '));
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000241 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000242 }
243 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000244
245 /// \brief Stores \p Text as the replacement for the whitespace in front of
246 /// \p Tok.
247 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasper7b038a22013-01-30 09:46:12 +0000248 // Don't create a replacement, if it does not change anything.
249 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
250 Tok.WhiteSpaceLength) == Text)
251 return;
252
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000253 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
254 Tok.WhiteSpaceLength, Text));
255 }
256
257 SourceManager &SourceMgr;
258 tooling::Replacements Replaces;
259};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000260
Daniel Jasper37905f72013-02-21 15:00:29 +0000261static bool isVarDeclName(const AnnotatedToken &Tok) {
262 return Tok.Parent != NULL && Tok.is(tok::identifier) &&
263 (Tok.Parent->Type == TT_PointerOrReference ||
264 Tok.Parent->is(tok::identifier));
265}
266
Daniel Jasperf7935112012-12-03 18:12:45 +0000267class UnwrappedLineFormatter {
268public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000269 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000270 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000271 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000272 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000273 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000274 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000275 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000276
Manuel Klimek1abf7892013-01-04 23:34:14 +0000277 /// \brief Formats an \c UnwrappedLine.
278 ///
279 /// \returns The column after the last token in the last line of the
280 /// \c UnwrappedLine.
281 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000282 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000283 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000284 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000285 State.NextToken = &RootToken;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000286 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
287 !Style.BinPackParameters,
288 /*HasMultiParameterLine=*/ false));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000289 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000290 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000291 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000292 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000293 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000294
Manuel Klimek24998102013-01-16 14:55:28 +0000295 DEBUG({
296 DebugTokenState(*State.NextToken);
297 });
298
Daniel Jaspere9de2602012-12-06 09:56:08 +0000299 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000300 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000301
Daniel Jasper4b866272013-02-01 11:00:45 +0000302 // If everything fits on a single line, just put it there.
303 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
304 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000305 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000306 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000307 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000308 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000309
Daniel Jasperacc33662013-02-08 08:22:00 +0000310 // If the ObjC method declaration does not fit on a line, we should format
311 // it with one arg per line.
312 if (Line.Type == LT_ObjCMethodDecl)
313 State.Stack.back().BreakBeforeParameter = true;
314
Daniel Jasper4b866272013-02-01 11:00:45 +0000315 // Find best solution in solution space.
316 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000317 }
318
319private:
Manuel Klimek24998102013-01-16 14:55:28 +0000320 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
321 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000322 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
323 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000324 llvm::errs();
325 }
326
Daniel Jasper337816e2013-01-11 10:22:12 +0000327 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000328 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
329 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000330 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
331 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000332 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000333 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000334
Daniel Jasperf7935112012-12-03 18:12:45 +0000335 /// \brief The position to which a specific parenthesis level needs to be
336 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000337 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000338
Daniel Jaspere9de2602012-12-06 09:56:08 +0000339 /// \brief The position of the last space on each level.
340 ///
341 /// Used e.g. to break like:
342 /// functionCall(Parameter, otherCall(
343 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000344 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000345
Daniel Jaspere9de2602012-12-06 09:56:08 +0000346 /// \brief The position the first "<<" operator encountered on each level.
347 ///
348 /// Used to align "<<" operators. 0 if no such operator has been encountered
349 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000350 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000351
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000352 /// \brief Whether a newline needs to be inserted before the block's closing
353 /// brace.
354 ///
355 /// We only want to insert a newline before the closing brace if there also
356 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000357 bool BreakBeforeClosingBrace;
358
Daniel Jasperca6623b2013-01-28 12:45:14 +0000359 /// \brief The column of a \c ? in a conditional expression;
360 unsigned QuestionColumn;
361
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000362 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
363 /// lines, in this context.
364 bool AvoidBinPacking;
365
366 /// \brief Break after the next comma (or all the commas in this context if
367 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000368 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000369
370 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000371 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000372
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000373 /// \brief The position of the colon in an ObjC method declaration/call.
374 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +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 Jasper7b7877a2013-01-12 07:36:22 +0000395 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000396 }
397 };
398
399 /// \brief The current state when indenting a unwrapped line.
400 ///
401 /// As the indenting tries different combinations this is copied by value.
402 struct LineState {
403 /// \brief The number of used columns in the current line.
404 unsigned Column;
405
406 /// \brief The token that needs to be next formatted.
407 const AnnotatedToken *NextToken;
408
Daniel Jasperbbc84152013-01-29 11:27:30 +0000409 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000410 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000411 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000412 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000413
414 /// \brief \c true if this line contains a continued for-loop section.
415 bool LineContainsContinuedForLoopSection;
416
Daniel Jasper400adc62013-02-08 15:28:42 +0000417 /// \brief The level of nesting inside (), [], <> and {}.
418 unsigned ParenLevel;
419
Daniel Jasper40c36c52013-02-18 11:05:07 +0000420 /// \brief The \c ParenLevel at the start of this line.
421 unsigned StartOfLineLevel;
422
Manuel Klimek02f640a2013-02-20 15:25:48 +0000423 /// \brief The start column of the string literal, if we're in a string
424 /// literal sequence, 0 otherwise.
425 unsigned StartOfStringLiteral;
426
Daniel Jasper337816e2013-01-11 10:22:12 +0000427 /// \brief A stack keeping track of properties applying to parenthesis
428 /// levels.
429 std::vector<ParenState> Stack;
430
431 /// \brief Comparison operator to be able to used \c LineState in \c map.
432 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000433 if (NextToken != Other.NextToken)
434 return NextToken < Other.NextToken;
435 if (Column != Other.Column)
436 return Column < Other.Column;
437 if (VariablePos != Other.VariablePos)
438 return VariablePos < Other.VariablePos;
439 if (LineContainsContinuedForLoopSection !=
440 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000441 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000442 if (ParenLevel != Other.ParenLevel)
443 return ParenLevel < Other.ParenLevel;
444 if (StartOfLineLevel != Other.StartOfLineLevel)
445 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000446 if (StartOfStringLiteral != Other.StartOfStringLiteral)
447 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000448 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000449 }
450 };
451
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000452 /// \brief Appends the next token to \p State and updates information
453 /// necessary for indentation.
454 ///
455 /// Puts the token on the current line if \p Newline is \c true and adds a
456 /// line break and necessary indentation otherwise.
457 ///
458 /// If \p DryRun is \c false, also creates and stores the required
459 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000460 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000461 const AnnotatedToken &Current = *State.NextToken;
462 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000463 assert(State.Stack.size());
Daniel Jasperf7935112012-12-03 18:12:45 +0000464
Daniel Jasper4b866272013-02-01 11:00:45 +0000465 if (Current.Type == TT_ImplicitStringLiteral) {
466 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
467 State.NextToken->FormatTok.TokenLength;
468 if (State.NextToken->Children.empty())
469 State.NextToken = NULL;
470 else
471 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000472 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000473 }
474
Daniel Jasperf7935112012-12-03 18:12:45 +0000475 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000476 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000477 if (Current.is(tok::r_brace)) {
478 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000479 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000480 State.StartOfStringLiteral != 0) {
481 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000482 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000483 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000484 State.Stack.back().FirstLessLess != 0) {
485 State.Column = State.Stack.back().FirstLessLess;
486 } else if (State.ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000487 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000488 Current.is(tok::period) || Current.is(tok::arrow) ||
489 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000490 // Indent and extra 4 spaces after if we know the current expression is
491 // continued. Don't do that on the top level, as we already indent 4
492 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000493 State.Column = std::max(State.Stack.back().LastSpace,
494 State.Stack.back().Indent) + 4;
495 } else if (Current.Type == TT_ConditionalExpr) {
496 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000497 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000498 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
499 State.ParenLevel == 0)) {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000500 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000501 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
502 Current.Type == TT_StartOfName) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000503 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000504 } else if (Current.Type == TT_ObjCSelectorName) {
505 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
506 State.Column =
507 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
508 } else {
509 State.Column = State.Stack.back().Indent;
510 State.Stack.back().ColonPos =
511 State.Column + Current.FormatTok.TokenLength;
512 }
Daniel Jasper37905f72013-02-21 15:00:29 +0000513 } else if (Previous.Type == TT_ObjCMethodExpr || isVarDeclName(Current)) {
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000514 State.Column = State.Stack.back().Indent + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000515 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000516 State.Column = State.Stack.back().Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000517 }
518
Daniel Jasper54a86022013-02-15 11:07:25 +0000519 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000520 State.Stack.back().BreakBeforeParameter = true;
521 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
522 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000523 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000524
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000525 if (!DryRun) {
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000526 unsigned NewLines =
527 std::max(1u, std::min(Current.FormatTok.NewlinesBefore,
528 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000529 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000530 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000531 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000532 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000533 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000534 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000535 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000536
Daniel Jasper400adc62013-02-08 15:28:42 +0000537 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000538 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000539 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper400adc62013-02-08 15:28:42 +0000540 State.Stack.back().Indent += 2;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000541
542 // Any break on this level means that the parent level has been broken
543 // and we need to avoid bin packing there.
544 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
545 State.Stack[i].BreakBeforeParameter = true;
546 }
547 // If we break after {, we should also break before the corresponding }.
548 if (Previous.is(tok::l_brace))
549 State.Stack.back().BreakBeforeClosingBrace = true;
550
551 if (State.Stack.back().AvoidBinPacking) {
552 // If we are breaking after '(', '{', '<', this is not bin packing
553 // unless AllowAllParametersOfDeclarationOnNextLine is false.
554 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
555 Previous.Type != TT_TemplateOpener) ||
556 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
557 Line.MustBeDeclaration))
558 State.Stack.back().BreakBeforeParameter = true;
559 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 } else {
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000561 if (Current.is(tok::equal))
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000562 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000563
Daniel Jaspereef30492013-02-11 12:36:37 +0000564 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000565
Daniel Jasperf7935112012-12-03 18:12:45 +0000566 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000567 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000568
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000569 if (Current.Type == TT_ObjCSelectorName &&
570 State.Stack.back().ColonPos == 0) {
571 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
572 State.Column + Spaces + Current.FormatTok.TokenLength)
573 State.Stack.back().ColonPos =
574 State.Stack.back().Indent + Current.LongestObjCSelectorName;
575 else
576 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000577 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000578 }
579
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000580 if (Current.Type != TT_LineComment &&
581 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
582 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper400adc62013-02-08 15:28:42 +0000583 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper14e40ec2013-02-04 08:34:57 +0000584 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper400adc62013-02-08 15:28:42 +0000585 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000586
Daniel Jaspere9de2602012-12-06 09:56:08 +0000587 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000588 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
589 // Treat the condition inside an if as if it was a second function
590 // parameter, i.e. let nested calls have an indent of 4.
591 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper400adc62013-02-08 15:28:42 +0000592 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000593 // Top-level spaces are exempt as that mostly leads to better results.
594 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000595 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000596 Previous.Type == TT_ConditionalExpr ||
597 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000598 getPrecedence(Previous) != prec::Assignment)
599 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000600 else if (Previous.Type == TT_InheritanceColon)
601 State.Stack.back().Indent = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000602 else if (Previous.ParameterCount > 1 &&
603 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000604 Previous.is(tok::l_brace) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000605 Previous.Type == TT_TemplateOpener))
606 // If this function has multiple parameters, indent nested calls from
607 // the start of the first parameter.
608 State.Stack.back().LastSpace = State.Column;
Daniel Jaspere53beb22013-02-18 13:52:06 +0000609 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
610 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
611 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000612 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000613
Manuel Klimek1998ea22013-02-20 10:15:13 +0000614 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000615 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000616
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000617 /// \brief Mark the next token as consumed in \p State and modify its stacks
618 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000619 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000620 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000621 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000622
Daniel Jaspereead02b2013-02-14 08:42:54 +0000623 if (Current.Type == TT_InheritanceColon)
624 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000625 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
626 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000627 if (Current.is(tok::question))
628 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000629 if (Current.Type == TT_CtorInitializerColon) {
630 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
631 State.Stack.back().AvoidBinPacking = true;
632 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000633 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000634
Daniel Jasper400adc62013-02-08 15:28:42 +0000635 // Insert scopes created by fake parenthesis.
636 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
637 ParenState NewParenState = State.Stack.back();
638 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000639 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000640 State.Stack.push_back(NewParenState);
641 }
642
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000643 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000644 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000645 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
646 Current.is(tok::l_brace) ||
647 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000648 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000649 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000650 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000651 NewIndent = 2 + State.Stack.back().LastSpace;
652 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000653 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000654 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000655 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000656 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000657 State.Stack.push_back(
658 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
659 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000660 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000661 }
662
Daniel Jasperacc33662013-02-08 08:22:00 +0000663 // If this '[' opens an ObjC call, determine whether all parameters fit into
664 // one line and put one per line if they don't.
665 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
666 Current.MatchingParen != NULL) {
667 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
668 State.Stack.back().BreakBeforeParameter = true;
669 }
670
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000671 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000672 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000673 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
674 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
675 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000676 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000677 --State.ParenLevel;
678 }
679
680 // Remove scopes created by fake parenthesis.
681 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
682 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000683 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000684
Manuel Klimek0c915712013-02-20 15:32:58 +0000685 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000686 State.StartOfStringLiteral = State.Column;
687 } else if (Current.isNot(tok::comment)) {
688 State.StartOfStringLiteral = 0;
689 }
690
Manuel Klimek1998ea22013-02-20 10:15:13 +0000691 State.Column += Current.FormatTok.TokenLength;
692
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000693 if (State.NextToken->Children.empty())
694 State.NextToken = NULL;
695 else
696 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000697
Manuel Klimek1998ea22013-02-20 10:15:13 +0000698 return breakProtrudingToken(Current, State, DryRun);
699 }
700
701 /// \brief If the current token sticks out over the end of the line, break
702 /// it if possible.
703 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
704 bool DryRun) {
705 if (Current.isNot(tok::string_literal))
706 return 0;
707
708 unsigned Penalty = 0;
709 unsigned TailOffset = 0;
710 unsigned TailLength = Current.FormatTok.TokenLength;
711 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
712 unsigned OffsetFromStart = 0;
713 while (StartColumn + TailLength > getColumnLimit()) {
714 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
715 TailOffset, TailLength);
716 StringRef::size_type SplitPoint =
717 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
718 if (SplitPoint == StringRef::npos)
719 break;
720 assert(SplitPoint != 0);
721 // +2, because 'Text' starts after the opening quotes, and does not
722 // include the closing quote we need to insert.
723 unsigned WhitespaceStartColumn =
724 StartColumn + OffsetFromStart + SplitPoint + 2;
725 State.Stack.back().LastSpace = StartColumn;
726 if (!DryRun) {
727 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
728 Line.InPPDirective, StartColumn,
729 WhitespaceStartColumn, Style);
730 }
731 TailOffset += SplitPoint + 1;
732 TailLength -= SplitPoint + 1;
733 OffsetFromStart = 1;
734 Penalty += 100;
735 }
736 State.Column = StartColumn + TailLength;
737 return Penalty;
738 }
739
740 StringRef::size_type
741 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
742 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
743 return Text.rfind(' ', Offset);
Daniel Jasperf7935112012-12-03 18:12:45 +0000744 }
745
Daniel Jasper2df93312013-01-09 10:16:05 +0000746 unsigned getColumnLimit() {
747 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
748 }
749
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000750 /// \brief An edge in the solution space from \c Previous->State to \c State,
751 /// inserting a newline dependent on the \c NewLine.
752 struct StateNode {
753 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000754 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000755 LineState State;
756 bool NewLine;
757 StateNode *Previous;
758 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000759
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000760 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
761 ///
762 /// In case of equal penalties, we want to prefer states that were inserted
763 /// first. During state generation we make sure that we insert states first
764 /// that break the line as late as possible.
765 typedef std::pair<unsigned, unsigned> OrderedPenalty;
766
767 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
768 /// \c State has the given \c OrderedPenalty.
769 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
770
771 /// \brief The BFS queue type.
772 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
773 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000774
775 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000776 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000777 /// This implements a variant of Dijkstra's algorithm on the graph that spans
778 /// the solution space (\c LineStates are the nodes). The algorithm tries to
779 /// find the shortest path (the one with lowest penalty) from \p InitialState
780 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000781 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000782 std::set<LineState> Seen;
783
Daniel Jasper4b866272013-02-01 11:00:45 +0000784 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000785 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000786 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
787 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
788 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000789
790 // While not empty, take first element and follow edges.
791 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000792 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000793 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000794 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000795 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000796 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000797 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000798 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000799
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000800 if (!Seen.insert(Node->State).second)
801 // State already examined with lower penalty.
802 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000803
Manuel Klimekaf491072013-02-13 10:54:19 +0000804 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
805 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000806 }
807
808 if (Queue.empty())
809 // We were unable to find a solution, do nothing.
810 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000811 return 0;
812
Daniel Jasper4b866272013-02-01 11:00:45 +0000813 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000814 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000815 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000816
Daniel Jasper4b866272013-02-01 11:00:45 +0000817 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000818 return Queue.top().second->State.Column;
819 }
820
821 void reconstructPath(LineState &State, StateNode *Current) {
822 // FIXME: This recursive implementation limits the possible number
823 // of tokens per line if compiled into a binary with small stack space.
824 // To become more independent of stack frame limitations we would need
825 // to also change the TokenAnnotator.
826 if (Current->Previous == NULL)
827 return;
828 reconstructPath(State, Current->Previous);
829 DEBUG({
830 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000831 llvm::errs()
832 << "Penalty for splitting before "
833 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
834 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000835 }
836 });
837 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000838 }
839
Manuel Klimekaf491072013-02-13 10:54:19 +0000840 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000841 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000842 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000843 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000844 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
845 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000846 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000847 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000848 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000849 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000850 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000851 Penalty += PreviousNode->State.NextToken->SplitPenalty;
852
853 StateNode *Node = new (Allocator.Allocate())
854 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000855 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000856 if (Node->State.Column > getColumnLimit()) {
857 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000858 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000859 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000860
861 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
862 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000863 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000864
Daniel Jasper4b866272013-02-01 11:00:45 +0000865 /// \brief Returns \c true, if a line break after \p State is allowed.
866 bool canBreak(const LineState &State) {
867 if (!State.NextToken->CanBreakBefore &&
868 !(State.NextToken->is(tok::r_brace) &&
869 State.Stack.back().BreakBeforeClosingBrace))
870 return false;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000871 // This prevents breaks like:
872 // ...
873 // SomeParameter, OtherParameter).DoSomething(
874 // ...
875 // As they hide "DoSomething" and generally bad for readability.
876 if (State.NextToken->Parent->is(tok::l_paren) &&
877 State.ParenLevel <= State.StartOfLineLevel)
878 return false;
Daniel Jasper4b866272013-02-01 11:00:45 +0000879 // Trying to insert a parameter on a new line if there are already more than
880 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000881 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000882 State.Stack.back().AvoidBinPacking)
883 return false;
884 return true;
885 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000886
Daniel Jasper4b866272013-02-01 11:00:45 +0000887 /// \brief Returns \c true, if a line break after \p State is mandatory.
888 bool mustBreak(const LineState &State) {
889 if (State.NextToken->MustBreakBefore)
890 return true;
891 if (State.NextToken->is(tok::r_brace) &&
892 State.Stack.back().BreakBeforeClosingBrace)
893 return true;
894 if (State.NextToken->Parent->is(tok::semi) &&
895 State.LineContainsContinuedForLoopSection)
896 return true;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000897 if ((State.NextToken->Parent->is(tok::comma) ||
898 State.NextToken->Parent->is(tok::semi) ||
899 State.NextToken->is(tok::question) ||
900 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000901 State.Stack.back().BreakBeforeParameter &&
Daniel Jasper66e9dee2013-02-14 09:19:04 +0000902 !isTrailingComment(*State.NextToken) &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000903 State.NextToken->isNot(tok::r_paren) &&
904 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000905 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000906 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
907 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000908 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000909 State.NextToken->LongestObjCSelectorName == 0 &&
910 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000911 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000912 if ((State.NextToken->Type == TT_CtorInitializerColon ||
913 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000914 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000915 return true;
916 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000917 }
918
Daniel Jasperf7935112012-12-03 18:12:45 +0000919 FormatStyle Style;
920 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000921 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000922 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000923 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000924 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000925
926 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
927 QueueType Queue;
928 // Increasing count of \c StateNode items we have created. This is used
929 // to create a deterministic order independent of the container.
930 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000931};
932
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000933class LexerBasedFormatTokenSource : public FormatTokenSource {
934public:
935 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000936 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000937 IdentTable(Lex.getLangOpts()) {
938 Lex.SetKeepWhitespaceMode(true);
939 }
940
941 virtual FormatToken getNextToken() {
942 if (GreaterStashed) {
943 FormatTok.NewlinesBefore = 0;
944 FormatTok.WhiteSpaceStart =
945 FormatTok.Tok.getLocation().getLocWithOffset(1);
946 FormatTok.WhiteSpaceLength = 0;
947 GreaterStashed = false;
948 return FormatTok;
949 }
950
951 FormatTok = FormatToken();
952 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000953 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000954 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000955 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
956 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000957
958 // Consume and record whitespace until we find a significant token.
959 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000960 unsigned Newlines = Text.count('\n');
961 unsigned EscapedNewlines = Text.count("\\\n");
962 FormatTok.NewlinesBefore += Newlines;
963 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000964 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
965
966 if (FormatTok.Tok.is(tok::eof))
967 return FormatTok;
968 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000969 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000970 }
Manuel Klimekef920692013-01-07 07:56:50 +0000971
972 // Now FormatTok is the next non-whitespace token.
973 FormatTok.TokenLength = Text.size();
974
Manuel Klimek1abf7892013-01-04 23:34:14 +0000975 // In case the token starts with escaped newlines, we want to
976 // take them into account as whitespace - this pattern is quite frequent
977 // in macro definitions.
978 // FIXME: What do we want to do with other escaped spaces, and escaped
979 // spaces or newlines in the middle of tokens?
980 // FIXME: Add a more explicit test.
981 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000982 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000983 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000984 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000985 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000986 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000987 }
988
989 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000990 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000991 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000992 FormatTok.Tok.setKind(Info.getTokenID());
993 }
994
995 if (FormatTok.Tok.is(tok::greatergreater)) {
996 FormatTok.Tok.setKind(tok::greater);
997 GreaterStashed = true;
998 }
999
1000 return FormatTok;
1001 }
1002
Nico Weber29f9dea2013-02-11 15:32:15 +00001003 IdentifierTable &getIdentTable() { return IdentTable; }
1004
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001005private:
1006 FormatToken FormatTok;
1007 bool GreaterStashed;
1008 Lexer &Lex;
1009 SourceManager &SourceMgr;
1010 IdentifierTable IdentTable;
1011
1012 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001013 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001014 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1015 Tok.getLength());
1016 }
1017};
1018
Daniel Jasperf7935112012-12-03 18:12:45 +00001019class Formatter : public UnwrappedLineConsumer {
1020public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001021 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1022 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001024 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001025 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001026
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001027 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001028
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001029 void deriveLocalStyle() {
1030 unsigned CountBoundToVariable = 0;
1031 unsigned CountBoundToType = 0;
1032 bool HasCpp03IncompatibleFormat = false;
1033 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1034 if (AnnotatedLines[i].First.Children.empty())
1035 continue;
1036 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1037 while (!Tok->Children.empty()) {
1038 if (Tok->Type == TT_PointerOrReference) {
1039 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1040 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1041 if (SpacesBefore && !SpacesAfter)
1042 ++CountBoundToVariable;
1043 else if (!SpacesBefore && SpacesAfter)
1044 ++CountBoundToType;
1045 }
1046
Daniel Jasper400adc62013-02-08 15:28:42 +00001047 if (Tok->Type == TT_TemplateCloser &&
1048 Tok->Parent->Type == TT_TemplateCloser &&
1049 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001050 HasCpp03IncompatibleFormat = true;
1051 Tok = &Tok->Children[0];
1052 }
1053 }
1054 if (Style.DerivePointerBinding) {
1055 if (CountBoundToType > CountBoundToVariable)
1056 Style.PointerBindsToType = true;
1057 else if (CountBoundToType < CountBoundToVariable)
1058 Style.PointerBindsToType = false;
1059 }
1060 if (Style.Standard == FormatStyle::LS_Auto) {
1061 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1062 : FormatStyle::LS_Cpp03;
1063 }
1064 }
1065
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001067 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001068 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001069 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001070 unsigned PreviousEndOfLineColumn = 0;
Nico Weber29f9dea2013-02-11 15:32:15 +00001071 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1072 Tokens.getIdentTable().get("in"));
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001073 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001074 Annotator.annotate(AnnotatedLines[i]);
1075 }
1076 deriveLocalStyle();
1077 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1078 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001079 }
Manuel Klimekb95f5452013-02-08 17:38:27 +00001080 std::vector<int> IndentForLevel;
Daniel Jasper24570102013-02-14 09:58:41 +00001081 bool PreviousLineWasTouched = false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001082 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1083 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001084 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001085 const AnnotatedLine &TheLine = *I;
Daniel Jasper24570102013-02-14 09:58:41 +00001086 int Offset = getIndentOffset(TheLine.First);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001087 while (IndentForLevel.size() <= TheLine.Level)
1088 IndentForLevel.push_back(-1);
1089 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper55d7ba62013-02-18 13:08:03 +00001090 bool WasMoved =
1091 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1092 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasper24570102013-02-14 09:58:41 +00001093 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimekb95f5452013-02-08 17:38:27 +00001094 unsigned Indent = LevelIndent;
1095 if (static_cast<int>(Indent) + Offset >= 0)
1096 Indent += Offset;
1097 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1098 StructuralError) {
1099 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1100 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1101 } else {
1102 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1103 PreviousEndOfLineColumn);
1104 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001105 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001106 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001107 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001108 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001109 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimekb95f5452013-02-08 17:38:27 +00001110 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001111 PreviousLineWasTouched = true;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001112 } else {
Daniel Jasper22045622013-02-12 16:51:23 +00001113 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1114 TheLine.First.FormatTok.IsFirst) {
1115 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1116 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1117 unsigned LevelIndent = Indent;
1118 if (static_cast<int>(LevelIndent) - Offset >= 0)
1119 LevelIndent -= Offset;
1120 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasper24570102013-02-14 09:58:41 +00001121
1122 // Remove trailing whitespace of the previous line if it was touched.
1123 if (PreviousLineWasTouched)
1124 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1125 PreviousEndOfLineColumn);
Daniel Jasper22045622013-02-12 16:51:23 +00001126 }
Daniel Jasper24570102013-02-14 09:58:41 +00001127 // If we did not reformat this unwrapped line, the column at the end of
1128 // the last token is unchanged - thus, we can calculate the end of the
1129 // last token.
1130 PreviousEndOfLineColumn =
1131 SourceMgr.getSpellingColumnNumber(
1132 TheLine.Last->FormatTok.Tok.getLocation()) +
1133 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1134 SourceMgr, Lex.getLangOpts()) - 1;
1135 PreviousLineWasTouched = false;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001136 }
1137 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001138 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001139 }
1140
1141private:
Manuel Klimekb95f5452013-02-08 17:38:27 +00001142 /// \brief Get the indent of \p Level from \p IndentForLevel.
1143 ///
1144 /// \p IndentForLevel must contain the indent for the level \c l
1145 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1146 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001147 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001148 if (IndentForLevel[Level] != -1)
1149 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001150 if (Level == 0)
1151 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001152 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001153 }
1154
1155 /// \brief Get the offset of the line relatively to the level.
1156 ///
1157 /// For example, 'public:' labels in classes are offset by 1 or 2
1158 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001159 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001160 bool IsAccessModifier = false;
1161 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1162 RootToken.is(tok::kw_private))
1163 IsAccessModifier = true;
1164 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1165 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1166 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1167 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1168 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1169 IsAccessModifier = true;
1170
1171 if (IsAccessModifier)
1172 return Style.AccessModifierOffset;
1173 return 0;
1174 }
1175
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001176 /// \brief Tries to merge lines into one.
1177 ///
1178 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1179 /// if possible; note that \c I will be incremented when lines are merged.
1180 ///
1181 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001182 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001183 std::vector<AnnotatedLine>::iterator &I,
1184 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001185 // We can never merge stuff if there are trailing line comments.
1186 if (I->Last->Type == TT_LineComment)
1187 return;
1188
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001189 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1190 // If we already exceed the column limit, we set 'Limit' to 0. The different
1191 // tryMerge..() functions can then decide whether to still do merging.
1192 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001193
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001194 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001195 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001196
Daniel Jasper25837aa2013-01-14 14:14:23 +00001197 if (I->Last->is(tok::l_brace)) {
1198 tryMergeSimpleBlock(I, E, Limit);
1199 } else if (I->First.is(tok::kw_if)) {
1200 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001201 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1202 I->First.FormatTok.IsFirst)) {
1203 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001204 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001205 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001206 }
1207
Daniel Jasper39825ea2013-01-14 15:40:57 +00001208 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1209 std::vector<AnnotatedLine>::iterator E,
1210 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001211 if (Limit == 0)
1212 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001213 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001214 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1215 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001216 if (I + 2 != E && (I + 2)->InPPDirective &&
1217 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1218 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001219 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001220 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001221 join(Line, *(++I));
1222 }
1223
Daniel Jasper25837aa2013-01-14 14:14:23 +00001224 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1225 std::vector<AnnotatedLine>::iterator E,
1226 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001227 if (Limit == 0)
1228 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001229 if (!Style.AllowShortIfStatementsOnASingleLine)
1230 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001231 if ((I + 1)->InPPDirective != I->InPPDirective ||
1232 ((I + 1)->InPPDirective &&
1233 (I + 1)->First.FormatTok.HasUnescapedNewline))
1234 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001235 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001236 if (Line.Last->isNot(tok::r_paren))
1237 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001238 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001239 return;
1240 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1241 return;
1242 // Only inline simple if's (no nested if or else).
1243 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1244 return;
1245 join(Line, *(++I));
1246 }
1247
1248 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001249 std::vector<AnnotatedLine>::iterator E,
1250 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001251 // First, check that the current line allows merging. This is the case if
1252 // we're not in a control flow statement and the last token is an opening
1253 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001254 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001255 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001256 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1257 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1258 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1259 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001260 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001261 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1262 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001263 if (!AllowedTokens)
1264 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001265
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001266 AnnotatedToken *Tok = &(I + 1)->First;
1267 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001268 !Tok->MustBreakBefore) {
1269 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001270 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001271 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001272 join(Line, *(I + 1));
1273 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001274 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001275 // Check that we still have three lines and they fit into the limit.
1276 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1277 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001278 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001279
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001280 // Second, check that the next line does not contain any braces - if it
1281 // does, readability declines when putting it into a single line.
1282 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1283 return;
1284 do {
1285 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1286 return;
1287 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1288 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001289
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001290 // Last, check that the third line contains a single closing brace.
1291 Tok = &(I + 2)->First;
1292 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1293 Tok->MustBreakBefore)
1294 return;
1295
1296 join(Line, *(I + 1));
1297 join(Line, *(I + 2));
1298 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001299 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001300 }
1301
1302 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1303 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001304 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1305 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001306 }
1307
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001308 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001309 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001310 A.Last->Children.push_back(B.First);
1311 while (!A.Last->Children.empty()) {
1312 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001313 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001314 A.Last = &A.Last->Children[0];
1315 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001316 }
1317
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001318 bool touchesRanges(const AnnotatedLine &TheLine) {
1319 const FormatToken *First = &TheLine.First.FormatTok;
1320 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001321 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001322 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001323 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001324 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1325 Ranges[i].getBegin()) &&
1326 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1327 LineRange.getBegin()))
1328 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001329 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001330 return false;
1331 }
1332
1333 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001334 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001335 }
1336
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001337 /// \brief Add a new line and the required indent before the first Token
1338 /// of the \c UnwrappedLine if there was no structural parsing error.
1339 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimekb95f5452013-02-08 17:38:27 +00001340 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1341 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001342 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001343
Daniel Jasperbbc84152013-01-29 11:27:30 +00001344 unsigned Newlines =
1345 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001346 if (Newlines == 0 && !Tok.IsFirst)
1347 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001348
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001349 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001350 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001351 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001352 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1353 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001354 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001355 }
1356
Alexander Kornienko116ba682013-01-14 11:34:14 +00001357 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001358 FormatStyle Style;
1359 Lexer &Lex;
1360 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001361 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001362 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001363 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001364 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001365};
1366
Daniel Jasperbbc84152013-01-29 11:27:30 +00001367tooling::Replacements
1368reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1369 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001370 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001371 OwningPtr<DiagnosticConsumer> DiagPrinter;
1372 if (DiagClient == 0) {
1373 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1374 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1375 DiagClient = DiagPrinter.get();
1376 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001377 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001378 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001379 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001380 Diagnostics.setSourceManager(&SourceMgr);
1381 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001382 return formatter.format();
1383}
1384
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001385LangOptions getFormattingLangOpts() {
1386 LangOptions LangOpts;
1387 LangOpts.CPlusPlus = 1;
1388 LangOpts.CPlusPlus11 = 1;
1389 LangOpts.Bool = 1;
1390 LangOpts.ObjC1 = 1;
1391 LangOpts.ObjC2 = 1;
1392 return LangOpts;
1393}
1394
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001395} // namespace format
1396} // namespace clang