blob: 60fe957a1264b15eea4e2665d9a8b057c32481db [file] [log] [blame]
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Daniel Jasper32d28ee2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperbac016b2012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jaspera03ab102013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperbac016b2012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000064 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jaspera03ab102013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperbac016b2012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000077 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
78 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000079 return ChromiumStyle;
80}
81
Daniel Jasper15417ef2013-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 Jasperce3d1a62013-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 Jasperdcc2a622013-01-18 08:44:07 +000099/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000100///
Daniel Jasperdcc2a622013-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 Jasper821627e2013-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 Jasper15417ef2013-02-06 20:07:35 +0000118 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperdcc2a622013-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 Jasper474e4622013-02-06 22:04:05 +0000125 if (NewLines == 0)
126 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
127 else
128 Comments.back().MinColumn = Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000129 Comments.back().MaxColumn =
Daniel Jasper42f458d2013-02-13 19:25:54 +0000130 Style.ColumnLimit - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000131 return;
132 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000133 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000134
135 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000136 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000137 alignComments();
Manuel Klimek8092a942013-02-20 10:15:13 +0000138 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperdcc2a622013-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 Klimek8092a942013-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 Jasperdcc2a622013-01-18 08:44:07 +0000190 std::string NewLineText;
191 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000192 unsigned Offset =
193 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-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 Klimek8092a942013-02-20 10:15:13 +0000200 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000201 }
202
Daniel Jasperdcc2a622013-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 Jasper29f123b2013-02-08 15:28:42 +0000240 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000241 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000242 }
243 }
Daniel Jasperdcc2a622013-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 Jasperafcbd852013-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 Jasperdcc2a622013-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 Klimek3f8c7f32013-01-10 18:45:26 +0000260
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261class UnwrappedLineFormatter {
262public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000263 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000264 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000265 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000266 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000267 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000268 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000269 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270
Manuel Klimekd4397b92013-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 Jasper3b5943f2012-12-06 09:56:08 +0000276 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000277 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000278 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000279 State.NextToken = &RootToken;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000280 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
281 !Style.BinPackParameters,
282 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000283 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000284 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000285 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000286 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000287 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000288
Manuel Klimekca547db2013-01-16 14:55:28 +0000289 DEBUG({
290 DebugTokenState(*State.NextToken);
291 });
292
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000293 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000294 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000295
Daniel Jasper68ef0df2013-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 Jasper1321eb52012-12-18 21:05:13 +0000299 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000300 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000301 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000302 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000303
Daniel Jasperce3d1a62013-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 Jasper68ef0df2013-02-01 11:00:45 +0000309 // Find best solution in solution space.
310 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311 }
312
313private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000314 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
315 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000316 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
317 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000318 llvm::errs();
319 }
320
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000321 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000322 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
323 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000324 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
325 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000326 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper237d4c12013-02-23 21:01:55 +0000327 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000328
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 /// \brief The position to which a specific parenthesis level needs to be
330 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000331 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000332
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000338 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000339
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000344 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000345
Manuel Klimekc8c8a472013-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 Jasper604eb4c2013-01-11 10:22:12 +0000351 bool BreakBeforeClosingBrace;
352
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000353 /// \brief The column of a \c ? in a conditional expression;
354 unsigned QuestionColumn;
355
Daniel Jasperf343cab2013-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 Jasperce3d1a62013-02-08 08:22:00 +0000362 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000363
364 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000365 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000366
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000367 /// \brief The position of the colon in an ObjC method declaration/call.
368 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000369
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000370 bool operator<(const ParenState &Other) const {
371 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000372 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-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 Jasper7e9bf8c2013-01-11 11:37:55 +0000377 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
378 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000379 if (QuestionColumn != Other.QuestionColumn)
380 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000381 if (AvoidBinPacking != Other.AvoidBinPacking)
382 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000383 if (BreakBeforeParameter != Other.BreakBeforeParameter)
384 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000385 if (HasMultiParameterLine != Other.HasMultiParameterLine)
386 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000387 if (ColonPos != Other.ColonPos)
388 return ColonPos < Other.ColonPos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000389 return false;
Daniel Jasper604eb4c2013-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 Jasper1a1ce832013-01-29 11:27:30 +0000403 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000404 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000405 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000406 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000407
408 /// \brief \c true if this line contains a continued for-loop section.
409 bool LineContainsContinuedForLoopSection;
410
Daniel Jasper29f123b2013-02-08 15:28:42 +0000411 /// \brief The level of nesting inside (), [], <> and {}.
412 unsigned ParenLevel;
413
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000414 /// \brief The \c ParenLevel at the start of this line.
415 unsigned StartOfLineLevel;
416
Manuel Klimekb56b6d12013-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 Jasper604eb4c2013-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 Jasperd7896702013-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 Jaspera324a0e2012-12-21 14:37:20 +0000435 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-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 Klimekb56b6d12013-02-20 15:25:48 +0000440 if (StartOfStringLiteral != Other.StartOfStringLiteral)
441 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000442 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 }
444 };
445
Daniel Jasper20409152012-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 Klimek8092a942013-02-20 10:15:13 +0000454 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000455 const AnnotatedToken &Current = *State.NextToken;
456 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000457 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000458
Daniel Jasper68ef0df2013-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 Klimek8092a942013-02-20 10:15:13 +0000466 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000467 }
468
Daniel Jasperbac016b2012-12-03 18:12:45 +0000469 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000470 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000471 if (Current.is(tok::r_brace)) {
472 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000473 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000474 State.StartOfStringLiteral != 0) {
475 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000476 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000477 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-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 Jasper5f2173e2013-01-28 07:43:15 +0000481 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000482 Current.is(tok::period) || Current.is(tok::arrow) ||
483 Current.is(tok::question))) {
Daniel Jasper9c837d02013-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 Jasperbfe6fd42013-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 Jasper2e603772013-01-29 11:21:01 +0000491 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000492 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
493 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000494 State.Column = State.VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000495 } else if (Previous.ClosesTemplateDeclaration ||
496 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000497 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-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 Jasper3c08a812013-02-24 18:54:32 +0000507 } else if (Previous.Type == TT_ObjCMethodExpr ||
508 Current.Type == TT_StartOfName) {
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000509 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000510 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000511 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000512 }
513
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000514 if (Current.is(tok::question))
Daniel Jasper237d4c12013-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 Jasperce3d1a62013-02-08 08:22:00 +0000518 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000519
Manuel Klimek060143e2013-01-02 18:33:23 +0000520 if (!DryRun) {
Daniel Jasperc4615b72013-02-20 12:56:39 +0000521 unsigned NewLines =
522 std::max(1u, std::min(Current.FormatTok.NewlinesBefore,
523 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000524 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000525 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000526 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000527 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000528 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000529 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000530 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000531
Daniel Jasper29f123b2013-02-08 15:28:42 +0000532 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000533 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000534 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000535 State.Stack.back().Indent += 2;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000536
537 // Any break on this level means that the parent level has been broken
538 // and we need to avoid bin packing there.
539 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
540 State.Stack[i].BreakBeforeParameter = true;
541 }
542 // If we break after {, we should also break before the corresponding }.
543 if (Previous.is(tok::l_brace))
544 State.Stack.back().BreakBeforeClosingBrace = true;
545
546 if (State.Stack.back().AvoidBinPacking) {
547 // If we are breaking after '(', '{', '<', this is not bin packing
548 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000549 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000550 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
551 Line.MustBeDeclaration))
552 State.Stack.back().BreakBeforeParameter = true;
553 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000554 } else {
Daniel Jasper237d4c12013-02-23 21:01:55 +0000555 if (Current.is(tok::equal))
Daniel Jasper2e603772013-01-29 11:21:01 +0000556 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000557
Daniel Jasper729a7432013-02-11 12:36:37 +0000558 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000559
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000561 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000562
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000563 if (Current.Type == TT_ObjCSelectorName &&
564 State.Stack.back().ColonPos == 0) {
565 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
566 State.Column + Spaces + Current.FormatTok.TokenLength)
567 State.Stack.back().ColonPos =
568 State.Stack.back().Indent + Current.LongestObjCSelectorName;
569 else
570 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000571 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000572 }
573
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000574 if (Current.Type != TT_LineComment &&
575 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
576 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000577 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000578 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000579 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000580
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000581 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000582 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
583 // Treat the condition inside an if as if it was a second function
584 // parameter, i.e. let nested calls have an indent of 4.
585 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000586 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000587 // Top-level spaces are exempt as that mostly leads to better results.
588 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000589 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000590 Previous.Type == TT_ConditionalExpr ||
591 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000592 getPrecedence(Previous) != prec::Assignment)
593 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000594 else if (Previous.Type == TT_InheritanceColon)
595 State.Stack.back().Indent = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000596 else if (Previous.ParameterCount > 1 &&
597 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000598 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000599 Previous.Type == TT_TemplateOpener))
600 // If this function has multiple parameters, indent nested calls from
601 // the start of the first parameter.
602 State.Stack.back().LastSpace = State.Column;
Daniel Jasper82282dc2013-02-18 13:52:06 +0000603 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
604 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
605 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000606 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000607
Manuel Klimek8092a942013-02-20 10:15:13 +0000608 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000609 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000610
Daniel Jasper20409152012-12-04 14:54:30 +0000611 /// \brief Mark the next token as consumed in \p State and modify its stacks
612 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000613 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000614 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000615 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000616
Daniel Jasper6cabab42013-02-14 08:42:54 +0000617 if (Current.Type == TT_InheritanceColon)
618 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000619 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
620 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000621 if (Current.is(tok::question))
622 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000623 if (Current.Type == TT_CtorInitializerColon) {
624 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
625 State.Stack.back().AvoidBinPacking = true;
626 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000627 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000628
Daniel Jasper29f123b2013-02-08 15:28:42 +0000629 // Insert scopes created by fake parenthesis.
630 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
631 ParenState NewParenState = State.Stack.back();
632 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jasper237d4c12013-02-23 21:01:55 +0000633 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000634 State.Stack.push_back(NewParenState);
635 }
636
Daniel Jaspercf225b62012-12-24 13:43:52 +0000637 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000638 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000639 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
640 Current.is(tok::l_brace) ||
641 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000642 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000643 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000644 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000645 NewIndent = 2 + State.Stack.back().LastSpace;
646 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000647 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000648 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000649 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000650 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000651 State.Stack.push_back(
652 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
653 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000654 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000655 }
656
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000657 // If this '[' opens an ObjC call, determine whether all parameters fit into
658 // one line and put one per line if they don't.
659 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
660 Current.MatchingParen != NULL) {
661 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
662 State.Stack.back().BreakBeforeParameter = true;
663 }
664
Daniel Jaspercf225b62012-12-24 13:43:52 +0000665 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000666 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000667 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
668 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
669 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000670 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000671 --State.ParenLevel;
672 }
673
674 // Remove scopes created by fake parenthesis.
675 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
676 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000677 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000678
Manuel Klimeke9a62262013-02-20 15:32:58 +0000679 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000680 State.StartOfStringLiteral = State.Column;
681 } else if (Current.isNot(tok::comment)) {
682 State.StartOfStringLiteral = 0;
683 }
684
Manuel Klimek8092a942013-02-20 10:15:13 +0000685 State.Column += Current.FormatTok.TokenLength;
686
Daniel Jasper26f7e782013-01-08 14:56:18 +0000687 if (State.NextToken->Children.empty())
688 State.NextToken = NULL;
689 else
690 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000691
Manuel Klimek8092a942013-02-20 10:15:13 +0000692 return breakProtrudingToken(Current, State, DryRun);
693 }
694
695 /// \brief If the current token sticks out over the end of the line, break
696 /// it if possible.
697 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
698 bool DryRun) {
699 if (Current.isNot(tok::string_literal))
700 return 0;
701
702 unsigned Penalty = 0;
703 unsigned TailOffset = 0;
704 unsigned TailLength = Current.FormatTok.TokenLength;
705 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
706 unsigned OffsetFromStart = 0;
707 while (StartColumn + TailLength > getColumnLimit()) {
708 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
709 TailOffset, TailLength);
710 StringRef::size_type SplitPoint =
711 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
712 if (SplitPoint == StringRef::npos)
713 break;
714 assert(SplitPoint != 0);
715 // +2, because 'Text' starts after the opening quotes, and does not
716 // include the closing quote we need to insert.
717 unsigned WhitespaceStartColumn =
718 StartColumn + OffsetFromStart + SplitPoint + 2;
719 State.Stack.back().LastSpace = StartColumn;
720 if (!DryRun) {
721 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
722 Line.InPPDirective, StartColumn,
723 WhitespaceStartColumn, Style);
724 }
725 TailOffset += SplitPoint + 1;
726 TailLength -= SplitPoint + 1;
727 OffsetFromStart = 1;
728 Penalty += 100;
729 }
730 State.Column = StartColumn + TailLength;
731 return Penalty;
732 }
733
734 StringRef::size_type
735 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
736 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
737 return Text.rfind(' ', Offset);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000738 }
739
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000740 unsigned getColumnLimit() {
741 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
742 }
743
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000744 /// \brief An edge in the solution space from \c Previous->State to \c State,
745 /// inserting a newline dependent on the \c NewLine.
746 struct StateNode {
747 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000748 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000749 LineState State;
750 bool NewLine;
751 StateNode *Previous;
752 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000753
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000754 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
755 ///
756 /// In case of equal penalties, we want to prefer states that were inserted
757 /// first. During state generation we make sure that we insert states first
758 /// that break the line as late as possible.
759 typedef std::pair<unsigned, unsigned> OrderedPenalty;
760
761 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
762 /// \c State has the given \c OrderedPenalty.
763 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
764
765 /// \brief The BFS queue type.
766 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
767 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000768
769 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000770 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000771 /// This implements a variant of Dijkstra's algorithm on the graph that spans
772 /// the solution space (\c LineStates are the nodes). The algorithm tries to
773 /// find the shortest path (the one with lowest penalty) from \p InitialState
774 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000775 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000776 std::set<LineState> Seen;
777
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000778 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000779 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000780 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
781 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
782 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000783
784 // While not empty, take first element and follow edges.
785 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000786 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000787 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000788 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000789 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000790 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000791 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000792 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000793
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000794 if (!Seen.insert(Node->State).second)
795 // State already examined with lower penalty.
796 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000797
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000798 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
799 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000800 }
801
802 if (Queue.empty())
803 // We were unable to find a solution, do nothing.
804 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000805 return 0;
806
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000807 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000808 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000809 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000810
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000811 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000812 return Queue.top().second->State.Column;
813 }
814
815 void reconstructPath(LineState &State, StateNode *Current) {
816 // FIXME: This recursive implementation limits the possible number
817 // of tokens per line if compiled into a binary with small stack space.
818 // To become more independent of stack frame limitations we would need
819 // to also change the TokenAnnotator.
820 if (Current->Previous == NULL)
821 return;
822 reconstructPath(State, Current->Previous);
823 DEBUG({
824 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000825 llvm::errs()
826 << "Penalty for splitting before "
827 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
828 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000829 }
830 });
831 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000832 }
833
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000834 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000835 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000836 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000837 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000838 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
839 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000840 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000841 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000842 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000843 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000844 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000845 Penalty += PreviousNode->State.NextToken->SplitPenalty;
846
847 StateNode *Node = new (Allocator.Allocate())
848 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000849 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000850 if (Node->State.Column > getColumnLimit()) {
851 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000852 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000853 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000854
855 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
856 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000857 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000859 /// \brief Returns \c true, if a line break after \p State is allowed.
860 bool canBreak(const LineState &State) {
861 if (!State.NextToken->CanBreakBefore &&
862 !(State.NextToken->is(tok::r_brace) &&
863 State.Stack.back().BreakBeforeClosingBrace))
864 return false;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000865 // This prevents breaks like:
866 // ...
867 // SomeParameter, OtherParameter).DoSomething(
868 // ...
869 // As they hide "DoSomething" and generally bad for readability.
870 if (State.NextToken->Parent->is(tok::l_paren) &&
871 State.ParenLevel <= State.StartOfLineLevel)
872 return false;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000873 // Trying to insert a parameter on a new line if there are already more than
874 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000875 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000876 State.Stack.back().AvoidBinPacking)
877 return false;
878 return true;
879 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000880
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000881 /// \brief Returns \c true, if a line break after \p State is mandatory.
882 bool mustBreak(const LineState &State) {
883 if (State.NextToken->MustBreakBefore)
884 return true;
885 if (State.NextToken->is(tok::r_brace) &&
886 State.Stack.back().BreakBeforeClosingBrace)
887 return true;
888 if (State.NextToken->Parent->is(tok::semi) &&
889 State.LineContainsContinuedForLoopSection)
890 return true;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000891 if ((State.NextToken->Parent->is(tok::comma) ||
892 State.NextToken->Parent->is(tok::semi) ||
893 State.NextToken->is(tok::question) ||
894 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000895 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc5cfa492013-02-14 09:19:04 +0000896 !isTrailingComment(*State.NextToken) &&
Daniel Jasper7d812812013-02-21 15:00:29 +0000897 State.NextToken->isNot(tok::r_paren) &&
898 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000899 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000900 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
901 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000902 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000903 State.NextToken->LongestObjCSelectorName == 0 &&
904 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000905 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000906 if ((State.NextToken->Type == TT_CtorInitializerColon ||
907 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000908 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000909 return true;
910 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000911 }
912
Daniel Jasperbac016b2012-12-03 18:12:45 +0000913 FormatStyle Style;
914 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000915 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000916 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000917 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000918 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000919
920 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
921 QueueType Queue;
922 // Increasing count of \c StateNode items we have created. This is used
923 // to create a deterministic order independent of the container.
924 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000925};
926
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000927class LexerBasedFormatTokenSource : public FormatTokenSource {
928public:
929 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000930 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000931 IdentTable(Lex.getLangOpts()) {
932 Lex.SetKeepWhitespaceMode(true);
933 }
934
935 virtual FormatToken getNextToken() {
936 if (GreaterStashed) {
937 FormatTok.NewlinesBefore = 0;
938 FormatTok.WhiteSpaceStart =
939 FormatTok.Tok.getLocation().getLocWithOffset(1);
940 FormatTok.WhiteSpaceLength = 0;
941 GreaterStashed = false;
942 return FormatTok;
943 }
944
945 FormatTok = FormatToken();
946 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000947 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000948 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000949 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
950 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000951
952 // Consume and record whitespace until we find a significant token.
953 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000954 unsigned Newlines = Text.count('\n');
955 unsigned EscapedNewlines = Text.count("\\\n");
956 FormatTok.NewlinesBefore += Newlines;
957 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000958 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
959
960 if (FormatTok.Tok.is(tok::eof))
961 return FormatTok;
962 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000963 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000964 }
Manuel Klimek95419382013-01-07 07:56:50 +0000965
966 // Now FormatTok is the next non-whitespace token.
967 FormatTok.TokenLength = Text.size();
968
Manuel Klimekd4397b92013-01-04 23:34:14 +0000969 // In case the token starts with escaped newlines, we want to
970 // take them into account as whitespace - this pattern is quite frequent
971 // in macro definitions.
972 // FIXME: What do we want to do with other escaped spaces, and escaped
973 // spaces or newlines in the middle of tokens?
974 // FIXME: Add a more explicit test.
975 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000976 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000977 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000978 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000979 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000980 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000981 }
982
983 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000984 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000985 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000986 FormatTok.Tok.setKind(Info.getTokenID());
987 }
988
989 if (FormatTok.Tok.is(tok::greatergreater)) {
990 FormatTok.Tok.setKind(tok::greater);
991 GreaterStashed = true;
992 }
993
994 return FormatTok;
995 }
996
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000997 IdentifierTable &getIdentTable() { return IdentTable; }
998
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000999private:
1000 FormatToken FormatTok;
1001 bool GreaterStashed;
1002 Lexer &Lex;
1003 SourceManager &SourceMgr;
1004 IdentifierTable IdentTable;
1005
1006 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001007 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001008 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1009 Tok.getLength());
1010 }
1011};
1012
Daniel Jasperbac016b2012-12-03 18:12:45 +00001013class Formatter : public UnwrappedLineConsumer {
1014public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001015 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1016 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001017 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001018 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperf11a7052013-02-21 21:33:55 +00001019 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001020
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001021 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001022
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001023 void deriveLocalStyle() {
1024 unsigned CountBoundToVariable = 0;
1025 unsigned CountBoundToType = 0;
1026 bool HasCpp03IncompatibleFormat = false;
1027 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1028 if (AnnotatedLines[i].First.Children.empty())
1029 continue;
1030 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1031 while (!Tok->Children.empty()) {
1032 if (Tok->Type == TT_PointerOrReference) {
1033 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1034 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1035 if (SpacesBefore && !SpacesAfter)
1036 ++CountBoundToVariable;
1037 else if (!SpacesBefore && SpacesAfter)
1038 ++CountBoundToType;
1039 }
1040
Daniel Jasper29f123b2013-02-08 15:28:42 +00001041 if (Tok->Type == TT_TemplateCloser &&
1042 Tok->Parent->Type == TT_TemplateCloser &&
1043 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001044 HasCpp03IncompatibleFormat = true;
1045 Tok = &Tok->Children[0];
1046 }
1047 }
1048 if (Style.DerivePointerBinding) {
1049 if (CountBoundToType > CountBoundToVariable)
1050 Style.PointerBindsToType = true;
1051 else if (CountBoundToType < CountBoundToVariable)
1052 Style.PointerBindsToType = false;
1053 }
1054 if (Style.Standard == FormatStyle::LS_Auto) {
1055 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1056 : FormatStyle::LS_Cpp03;
1057 }
1058 }
1059
Daniel Jasperbac016b2012-12-03 18:12:45 +00001060 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001061 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001062 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001063 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001064 unsigned PreviousEndOfLineColumn = 0;
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001065 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1066 Tokens.getIdentTable().get("in"));
Daniel Jasper995e8202013-01-14 13:08:07 +00001067 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001068 Annotator.annotate(AnnotatedLines[i]);
1069 }
1070 deriveLocalStyle();
1071 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1072 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +00001073 }
Manuel Klimek547d5db2013-02-08 17:38:27 +00001074 std::vector<int> IndentForLevel;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001075 bool PreviousLineWasTouched = false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001076 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1077 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001078 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001079 const AnnotatedLine &TheLine = *I;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001080 int Offset = getIndentOffset(TheLine.First);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001081 while (IndentForLevel.size() <= TheLine.Level)
1082 IndentForLevel.push_back(-1);
1083 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper29333162013-02-18 13:08:03 +00001084 bool WasMoved =
1085 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1086 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001087 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001088 unsigned Indent = LevelIndent;
1089 if (static_cast<int>(Indent) + Offset >= 0)
1090 Indent += Offset;
1091 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1092 StructuralError) {
1093 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1094 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1095 } else {
1096 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1097 PreviousEndOfLineColumn);
1098 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001099 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001100 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001101 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001102 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001103 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimek547d5db2013-02-08 17:38:27 +00001104 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001105 PreviousLineWasTouched = true;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001106 } else {
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001107 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1108 TheLine.First.FormatTok.IsFirst) {
1109 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1110 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1111 unsigned LevelIndent = Indent;
1112 if (static_cast<int>(LevelIndent) - Offset >= 0)
1113 LevelIndent -= Offset;
1114 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001115
1116 // Remove trailing whitespace of the previous line if it was touched.
1117 if (PreviousLineWasTouched)
1118 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1119 PreviousEndOfLineColumn);
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001120 }
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001121 // If we did not reformat this unwrapped line, the column at the end of
1122 // the last token is unchanged - thus, we can calculate the end of the
1123 // last token.
1124 PreviousEndOfLineColumn =
1125 SourceMgr.getSpellingColumnNumber(
1126 TheLine.Last->FormatTok.Tok.getLocation()) +
1127 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1128 SourceMgr, Lex.getLangOpts()) - 1;
1129 PreviousLineWasTouched = false;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001130 }
1131 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001132 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001133 }
1134
1135private:
Manuel Klimek547d5db2013-02-08 17:38:27 +00001136 /// \brief Get the indent of \p Level from \p IndentForLevel.
1137 ///
1138 /// \p IndentForLevel must contain the indent for the level \c l
1139 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1140 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001141 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001142 if (IndentForLevel[Level] != -1)
1143 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001144 if (Level == 0)
1145 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001146 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001147 }
1148
1149 /// \brief Get the offset of the line relatively to the level.
1150 ///
1151 /// For example, 'public:' labels in classes are offset by 1 or 2
1152 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001153 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001154 bool IsAccessModifier = false;
1155 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1156 RootToken.is(tok::kw_private))
1157 IsAccessModifier = true;
1158 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1159 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1160 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1161 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1162 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1163 IsAccessModifier = true;
1164
1165 if (IsAccessModifier)
1166 return Style.AccessModifierOffset;
1167 return 0;
1168 }
1169
Manuel Klimek517e8942013-01-11 17:54:10 +00001170 /// \brief Tries to merge lines into one.
1171 ///
1172 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1173 /// if possible; note that \c I will be incremented when lines are merged.
1174 ///
1175 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001176 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001177 std::vector<AnnotatedLine>::iterator &I,
1178 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001179 // We can never merge stuff if there are trailing line comments.
1180 if (I->Last->Type == TT_LineComment)
1181 return;
1182
Daniel Jasperf11a7052013-02-21 21:33:55 +00001183 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1184 // If we already exceed the column limit, we set 'Limit' to 0. The different
1185 // tryMerge..() functions can then decide whether to still do merging.
1186 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001187
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001188 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001189 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001190
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001191 if (I->Last->is(tok::l_brace)) {
1192 tryMergeSimpleBlock(I, E, Limit);
1193 } else if (I->First.is(tok::kw_if)) {
1194 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001195 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1196 I->First.FormatTok.IsFirst)) {
1197 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001198 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001199 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001200 }
1201
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001202 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1203 std::vector<AnnotatedLine>::iterator E,
1204 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001205 if (Limit == 0)
1206 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001207 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001208 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1209 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001210 if (I + 2 != E && (I + 2)->InPPDirective &&
1211 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1212 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001213 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001214 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001215 join(Line, *(++I));
1216 }
1217
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001218 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1219 std::vector<AnnotatedLine>::iterator E,
1220 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001221 if (Limit == 0)
1222 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001223 if (!Style.AllowShortIfStatementsOnASingleLine)
1224 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001225 if ((I + 1)->InPPDirective != I->InPPDirective ||
1226 ((I + 1)->InPPDirective &&
1227 (I + 1)->First.FormatTok.HasUnescapedNewline))
1228 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001229 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001230 if (Line.Last->isNot(tok::r_paren))
1231 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001232 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001233 return;
1234 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1235 return;
1236 // Only inline simple if's (no nested if or else).
1237 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1238 return;
1239 join(Line, *(++I));
1240 }
1241
1242 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001243 std::vector<AnnotatedLine>::iterator E,
1244 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001245 // First, check that the current line allows merging. This is the case if
1246 // we're not in a control flow statement and the last token is an opening
1247 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001248 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001249 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001250 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1251 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1252 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1253 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001254 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001255 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1256 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001257 if (!AllowedTokens)
1258 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001259
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001260 AnnotatedToken *Tok = &(I + 1)->First;
1261 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001262 !Tok->MustBreakBefore) {
1263 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001264 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001265 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001266 join(Line, *(I + 1));
1267 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001268 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001269 // Check that we still have three lines and they fit into the limit.
1270 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1271 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001272 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001273
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001274 // Second, check that the next line does not contain any braces - if it
1275 // does, readability declines when putting it into a single line.
1276 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1277 return;
1278 do {
1279 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1280 return;
1281 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1282 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001283
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001284 // Last, check that the third line contains a single closing brace.
1285 Tok = &(I + 2)->First;
1286 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1287 Tok->MustBreakBefore)
1288 return;
1289
1290 join(Line, *(I + 1));
1291 join(Line, *(I + 2));
1292 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001293 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001294 }
1295
1296 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1297 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001298 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1299 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001300 }
1301
Daniel Jasper995e8202013-01-14 13:08:07 +00001302 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001303 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001304 A.Last->Children.push_back(B.First);
1305 while (!A.Last->Children.empty()) {
1306 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001307 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001308 A.Last = &A.Last->Children[0];
1309 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001310 }
1311
Daniel Jasper995e8202013-01-14 13:08:07 +00001312 bool touchesRanges(const AnnotatedLine &TheLine) {
1313 const FormatToken *First = &TheLine.First.FormatTok;
1314 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001315 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001316 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001317 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001318 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1319 Ranges[i].getBegin()) &&
1320 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1321 LineRange.getBegin()))
1322 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001323 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001324 return false;
1325 }
1326
1327 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001328 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001329 }
1330
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001331 /// \brief Add a new line and the required indent before the first Token
1332 /// of the \c UnwrappedLine if there was no structural parsing error.
1333 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek547d5db2013-02-08 17:38:27 +00001334 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1335 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001336 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001337
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001338 unsigned Newlines =
1339 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001340 if (Newlines == 0 && !Tok.IsFirst)
1341 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001342
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001343 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001344 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001345 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001346 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1347 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001348 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001349 }
1350
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001351 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001352 FormatStyle Style;
1353 Lexer &Lex;
1354 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001355 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001356 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001357 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001358 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001359};
1360
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001361tooling::Replacements
1362reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1363 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001364 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001365 OwningPtr<DiagnosticConsumer> DiagPrinter;
1366 if (DiagClient == 0) {
1367 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1368 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1369 DiagClient = DiagPrinter.get();
1370 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001371 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001372 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001373 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001374 Diagnostics.setSourceManager(&SourceMgr);
1375 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001376 return formatter.format();
1377}
1378
Daniel Jasper46ef8522013-01-10 13:08:12 +00001379LangOptions getFormattingLangOpts() {
1380 LangOptions LangOpts;
1381 LangOpts.CPlusPlus = 1;
1382 LangOpts.CPlusPlus11 = 1;
1383 LangOpts.Bool = 1;
1384 LangOpts.ObjC1 = 1;
1385 LangOpts.ObjC2 = 1;
1386 return LangOpts;
1387}
1388
Daniel Jaspercd162382013-01-07 13:26:07 +00001389} // namespace format
1390} // namespace clang