blob: 625f93151ffed3b214a6fdf4f87bb2c6c7749974 [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),
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000269 Whitespaces(Whitespaces), Count(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270 }
271
Manuel Klimekd4397b92013-01-04 23:34:14 +0000272 /// \brief Formats an \c UnwrappedLine.
273 ///
274 /// \returns The column after the last token in the last line of the
275 /// \c UnwrappedLine.
276 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000277 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000278 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000279 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000280 State.NextToken = &RootToken;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000281 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
282 !Style.BinPackParameters,
283 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000284 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000285 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000286 State.ParenLevel = 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 Jasper7878a7b2013-02-15 11:07:25 +0000327 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
328 BreakBeforeThirdOperand(false) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000329 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000330
Daniel Jasperbac016b2012-12-03 18:12:45 +0000331 /// \brief The position to which a specific parenthesis level needs to be
332 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000333 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000334
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000335 /// \brief The position of the last space on each level.
336 ///
337 /// Used e.g. to break like:
338 /// functionCall(Parameter, otherCall(
339 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000340 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000342 /// \brief The position the first "<<" operator encountered on each level.
343 ///
344 /// Used to align "<<" operators. 0 if no such operator has been encountered
345 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000346 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000347
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000348 /// \brief Whether a newline needs to be inserted before the block's closing
349 /// brace.
350 ///
351 /// We only want to insert a newline before the closing brace if there also
352 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000353 bool BreakBeforeClosingBrace;
354
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000355 /// \brief The column of a \c ? in a conditional expression;
356 unsigned QuestionColumn;
357
Daniel Jasperf343cab2013-01-31 14:59:26 +0000358 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
359 /// lines, in this context.
360 bool AvoidBinPacking;
361
362 /// \brief Break after the next comma (or all the commas in this context if
363 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000364 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000365
366 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000367 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000368
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000369 /// \brief The position of the colon in an ObjC method declaration/call.
370 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000371
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000372 /// \brief Break before third operand in ternary expression.
373 bool BreakBeforeThirdOperand;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000374
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000375 bool operator<(const ParenState &Other) const {
376 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000377 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000378 if (LastSpace != Other.LastSpace)
379 return LastSpace < Other.LastSpace;
380 if (FirstLessLess != Other.FirstLessLess)
381 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000382 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
383 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000384 if (QuestionColumn != Other.QuestionColumn)
385 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000386 if (AvoidBinPacking != Other.AvoidBinPacking)
387 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000388 if (BreakBeforeParameter != Other.BreakBeforeParameter)
389 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000390 if (HasMultiParameterLine != Other.HasMultiParameterLine)
391 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000392 if (ColonPos != Other.ColonPos)
393 return ColonPos < Other.ColonPos;
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000394 if (BreakBeforeThirdOperand != Other.BreakBeforeThirdOperand)
395 return BreakBeforeThirdOperand;
Daniel Jasperb3123142013-01-12 07:36:22 +0000396 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000397 }
398 };
399
400 /// \brief The current state when indenting a unwrapped line.
401 ///
402 /// As the indenting tries different combinations this is copied by value.
403 struct LineState {
404 /// \brief The number of used columns in the current line.
405 unsigned Column;
406
407 /// \brief The token that needs to be next formatted.
408 const AnnotatedToken *NextToken;
409
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000410 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000411 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000412 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000413 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000414
415 /// \brief \c true if this line contains a continued for-loop section.
416 bool LineContainsContinuedForLoopSection;
417
Daniel Jasper29f123b2013-02-08 15:28:42 +0000418 /// \brief The level of nesting inside (), [], <> and {}.
419 unsigned ParenLevel;
420
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000421 /// \brief The \c ParenLevel at the start of this line.
422 unsigned StartOfLineLevel;
423
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000424 /// \brief A stack keeping track of properties applying to parenthesis
425 /// levels.
426 std::vector<ParenState> Stack;
427
428 /// \brief Comparison operator to be able to used \c LineState in \c map.
429 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000430 if (NextToken != Other.NextToken)
431 return NextToken < Other.NextToken;
432 if (Column != Other.Column)
433 return Column < Other.Column;
434 if (VariablePos != Other.VariablePos)
435 return VariablePos < Other.VariablePos;
436 if (LineContainsContinuedForLoopSection !=
437 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000438 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000439 if (ParenLevel != Other.ParenLevel)
440 return ParenLevel < Other.ParenLevel;
441 if (StartOfLineLevel != Other.StartOfLineLevel)
442 return StartOfLineLevel < Other.StartOfLineLevel;
443 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000444 }
445 };
446
Daniel Jasper20409152012-12-04 14:54:30 +0000447 /// \brief Appends the next token to \p State and updates information
448 /// necessary for indentation.
449 ///
450 /// Puts the token on the current line if \p Newline is \c true and adds a
451 /// line break and necessary indentation otherwise.
452 ///
453 /// If \p DryRun is \c false, also creates and stores the required
454 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000455 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000456 const AnnotatedToken &Current = *State.NextToken;
457 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000458 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000459
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000460 if (Current.Type == TT_ImplicitStringLiteral) {
461 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
462 State.NextToken->FormatTok.TokenLength;
463 if (State.NextToken->Children.empty())
464 State.NextToken = NULL;
465 else
466 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000467 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000468 }
469
Daniel Jasperbac016b2012-12-03 18:12:45 +0000470 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000471 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000472 if (Current.is(tok::r_brace)) {
473 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000474 } else if (Current.is(tok::string_literal) &&
475 Previous.is(tok::string_literal)) {
476 State.Column = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000477 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000478 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000479 State.Stack.back().FirstLessLess != 0) {
480 State.Column = State.Stack.back().FirstLessLess;
481 } else if (State.ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000482 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000483 Current.is(tok::period) || Current.is(tok::arrow) ||
484 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000485 // Indent and extra 4 spaces after if we know the current expression is
486 // continued. Don't do that on the top level, as we already indent 4
487 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000488 State.Column = std::max(State.Stack.back().LastSpace,
489 State.Stack.back().Indent) + 4;
490 } else if (Current.Type == TT_ConditionalExpr) {
491 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000492 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000493 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
494 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000495 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000496 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
497 Current.Type == TT_StartOfName) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000498 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000499 } else if (Current.Type == TT_ObjCSelectorName) {
500 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
501 State.Column =
502 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
503 } else {
504 State.Column = State.Stack.back().Indent;
505 State.Stack.back().ColonPos =
506 State.Column + Current.FormatTok.TokenLength;
507 }
508 } else if (Previous.Type == TT_ObjCMethodExpr) {
509 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))
515 State.Stack.back().BreakBeforeThirdOperand = true;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000516 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000517 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000518
Daniel Jasper26f7e782013-01-08 14:56:18 +0000519 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000520 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000521
Manuel Klimek060143e2013-01-02 18:33:23 +0000522 if (!DryRun) {
Daniel Jasperc4615b72013-02-20 12:56:39 +0000523 unsigned NewLines =
524 std::max(1u, std::min(Current.FormatTok.NewlinesBefore,
525 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000526 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000527 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000528 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000529 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000530 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000531 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000532 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000533
Daniel Jasper29f123b2013-02-08 15:28:42 +0000534 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000535 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000536 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000537 State.Stack.back().Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000538 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000539 if (Current.is(tok::equal) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000540 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000541 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000542
Daniel Jasper729a7432013-02-11 12:36:37 +0000543 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000544
Daniel Jasperbac016b2012-12-03 18:12:45 +0000545 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000546 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000547
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000548 if (Current.Type == TT_ObjCSelectorName &&
549 State.Stack.back().ColonPos == 0) {
550 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
551 State.Column + Spaces + Current.FormatTok.TokenLength)
552 State.Stack.back().ColonPos =
553 State.Stack.back().Indent + Current.LongestObjCSelectorName;
554 else
555 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000556 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000557 }
558
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000559 if (Current.Type != TT_LineComment &&
560 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
561 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000562 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000563 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000564 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000565
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000566 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000567 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
568 // Treat the condition inside an if as if it was a second function
569 // parameter, i.e. let nested calls have an indent of 4.
570 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000571 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000572 // Top-level spaces are exempt as that mostly leads to better results.
573 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000574 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000575 Previous.Type == TT_ConditionalExpr ||
576 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000577 getPrecedence(Previous) != prec::Assignment)
578 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000579 else if (Previous.Type == TT_InheritanceColon)
580 State.Stack.back().Indent = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000581 else if (Previous.ParameterCount > 1 &&
582 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000583 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000584 Previous.Type == TT_TemplateOpener))
585 // If this function has multiple parameters, indent nested calls from
586 // the start of the first parameter.
587 State.Stack.back().LastSpace = State.Column;
Daniel Jasper82282dc2013-02-18 13:52:06 +0000588 else if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
589 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
590 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000592
593 // If we break after an {, we should also break before the corresponding }.
594 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000595 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000596
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000597 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000598 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000599 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000600 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000601 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
602 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000603 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
604 Line.MustBeDeclaration))
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000605 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000606
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000607 // Any break on this level means that the parent level has been broken
608 // and we need to avoid bin packing there.
609 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000610 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000611 State.Stack[i].BreakBeforeParameter = true;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000612 }
613 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000614
Manuel Klimek8092a942013-02-20 10:15:13 +0000615 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000616 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000617
Daniel Jasper20409152012-12-04 14:54:30 +0000618 /// \brief Mark the next token as consumed in \p State and modify its stacks
619 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000620 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000621 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000622 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000623
Daniel Jasper6cabab42013-02-14 08:42:54 +0000624 if (Current.Type == TT_InheritanceColon)
625 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000626 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
627 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000628 if (Current.is(tok::question))
629 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasperb130a542013-02-15 16:49:44 +0000630 if (Current.Type == TT_CtorInitializerColon &&
631 Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
632 State.Stack.back().AvoidBinPacking = true;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000633 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasperf343cab2013-01-31 14:59:26 +0000634 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000635 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
636 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000637 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000638
Daniel Jasper29f123b2013-02-08 15:28:42 +0000639 // Insert scopes created by fake parenthesis.
640 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
641 ParenState NewParenState = State.Stack.back();
642 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
643 State.Stack.push_back(NewParenState);
644 }
645
Daniel Jaspercf225b62012-12-24 13:43:52 +0000646 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000647 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000648 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
649 Current.is(tok::l_brace) ||
650 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000651 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000652 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000653 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000654 NewIndent = 2 + State.Stack.back().LastSpace;
655 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000656 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000657 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000658 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000659 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000660 State.Stack.push_back(
661 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
662 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000663 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000664 }
665
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000666 // If this '[' opens an ObjC call, determine whether all parameters fit into
667 // one line and put one per line if they don't.
668 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
669 Current.MatchingParen != NULL) {
670 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
671 State.Stack.back().BreakBeforeParameter = true;
672 }
673
Daniel Jaspercf225b62012-12-24 13:43:52 +0000674 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000675 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000676 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
677 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
678 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000679 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000680 --State.ParenLevel;
681 }
682
683 // Remove scopes created by fake parenthesis.
684 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
685 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000686 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000687
Manuel Klimek8092a942013-02-20 10:15:13 +0000688 State.Column += Current.FormatTok.TokenLength;
689
Daniel Jasper26f7e782013-01-08 14:56:18 +0000690 if (State.NextToken->Children.empty())
691 State.NextToken = NULL;
692 else
693 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000694
Manuel Klimek8092a942013-02-20 10:15:13 +0000695 return breakProtrudingToken(Current, State, DryRun);
696 }
697
698 /// \brief If the current token sticks out over the end of the line, break
699 /// it if possible.
700 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
701 bool DryRun) {
702 if (Current.isNot(tok::string_literal))
703 return 0;
704
705 unsigned Penalty = 0;
706 unsigned TailOffset = 0;
707 unsigned TailLength = Current.FormatTok.TokenLength;
708 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
709 unsigned OffsetFromStart = 0;
710 while (StartColumn + TailLength > getColumnLimit()) {
711 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
712 TailOffset, TailLength);
713 StringRef::size_type SplitPoint =
714 getSplitPoint(Text, getColumnLimit() - StartColumn - 1);
715 if (SplitPoint == StringRef::npos)
716 break;
717 assert(SplitPoint != 0);
718 // +2, because 'Text' starts after the opening quotes, and does not
719 // include the closing quote we need to insert.
720 unsigned WhitespaceStartColumn =
721 StartColumn + OffsetFromStart + SplitPoint + 2;
722 State.Stack.back().LastSpace = StartColumn;
723 if (!DryRun) {
724 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
725 Line.InPPDirective, StartColumn,
726 WhitespaceStartColumn, Style);
727 }
728 TailOffset += SplitPoint + 1;
729 TailLength -= SplitPoint + 1;
730 OffsetFromStart = 1;
731 Penalty += 100;
732 }
733 State.Column = StartColumn + TailLength;
734 return Penalty;
735 }
736
737 StringRef::size_type
738 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
739 // FIXME: Implement more sophisticated splitting mechanism, and a fallback.
740 return Text.rfind(' ', Offset);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 }
742
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000743 unsigned getColumnLimit() {
744 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
745 }
746
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000747 /// \brief An edge in the solution space from \c Previous->State to \c State,
748 /// inserting a newline dependent on the \c NewLine.
749 struct StateNode {
750 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
751 : State(State), NewLine(NewLine), Previous(Previous) {
752 }
753 LineState State;
754 bool NewLine;
755 StateNode *Previous;
756 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000757
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000758 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
759 ///
760 /// In case of equal penalties, we want to prefer states that were inserted
761 /// first. During state generation we make sure that we insert states first
762 /// that break the line as late as possible.
763 typedef std::pair<unsigned, unsigned> OrderedPenalty;
764
765 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
766 /// \c State has the given \c OrderedPenalty.
767 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
768
769 /// \brief The BFS queue type.
770 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
771 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000772
773 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000774 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000775 /// This implements a variant of Dijkstra's algorithm on the graph that spans
776 /// the solution space (\c LineStates are the nodes). The algorithm tries to
777 /// find the shortest path (the one with lowest penalty) from \p InitialState
778 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000779 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000780 std::set<LineState> Seen;
781
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000782 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000783 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000784 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
785 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
786 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000787
788 // While not empty, take first element and follow edges.
789 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000790 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000791 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000792 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000793 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000794 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000795 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000796 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000797
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000798 if (!Seen.insert(Node->State).second)
799 // State already examined with lower penalty.
800 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000801
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000802 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
803 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000804 }
805
806 if (Queue.empty())
807 // We were unable to find a solution, do nothing.
808 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809 return 0;
810
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000811 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000812 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000813 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000814
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000815 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000816 return Queue.top().second->State.Column;
817 }
818
819 void reconstructPath(LineState &State, StateNode *Current) {
820 // FIXME: This recursive implementation limits the possible number
821 // of tokens per line if compiled into a binary with small stack space.
822 // To become more independent of stack frame limitations we would need
823 // to also change the TokenAnnotator.
824 if (Current->Previous == NULL)
825 return;
826 reconstructPath(State, Current->Previous);
827 DEBUG({
828 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000829 llvm::errs()
830 << "Penalty for splitting before "
831 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
832 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000833 }
834 });
835 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000836 }
837
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000838 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000839 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000840 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000841 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000842 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
843 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000844 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000845 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000846 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000847 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000848 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000849 Penalty += PreviousNode->State.NextToken->SplitPenalty;
850
851 StateNode *Node = new (Allocator.Allocate())
852 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000853 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000854 if (Node->State.Column > getColumnLimit()) {
855 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000856 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000857 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000858
859 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
860 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000861 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000862
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000863 /// \brief Returns \c true, if a line break after \p State is allowed.
864 bool canBreak(const LineState &State) {
865 if (!State.NextToken->CanBreakBefore &&
866 !(State.NextToken->is(tok::r_brace) &&
867 State.Stack.back().BreakBeforeClosingBrace))
868 return false;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000869 // This prevents breaks like:
870 // ...
871 // SomeParameter, OtherParameter).DoSomething(
872 // ...
873 // As they hide "DoSomething" and generally bad for readability.
874 if (State.NextToken->Parent->is(tok::l_paren) &&
875 State.ParenLevel <= State.StartOfLineLevel)
876 return false;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000877 // Trying to insert a parameter on a new line if there are already more than
878 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000879 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000880 State.Stack.back().AvoidBinPacking)
881 return false;
882 return true;
883 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000884
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000885 /// \brief Returns \c true, if a line break after \p State is mandatory.
886 bool mustBreak(const LineState &State) {
887 if (State.NextToken->MustBreakBefore)
888 return true;
889 if (State.NextToken->is(tok::r_brace) &&
890 State.Stack.back().BreakBeforeClosingBrace)
891 return true;
892 if (State.NextToken->Parent->is(tok::semi) &&
893 State.LineContainsContinuedForLoopSection)
894 return true;
895 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000896 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc5cfa492013-02-14 09:19:04 +0000897 !isTrailingComment(*State.NextToken) &&
898 State.NextToken->isNot(tok::r_paren))
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;
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000910 if (State.NextToken->is(tok::colon) &&
911 State.Stack.back().BreakBeforeThirdOperand)
912 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000913 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000914 }
915
Daniel Jasperbac016b2012-12-03 18:12:45 +0000916 FormatStyle Style;
917 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000918 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000919 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000920 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000921 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000922
923 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
924 QueueType Queue;
925 // Increasing count of \c StateNode items we have created. This is used
926 // to create a deterministic order independent of the container.
927 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000928};
929
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000930class LexerBasedFormatTokenSource : public FormatTokenSource {
931public:
932 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000933 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000934 IdentTable(Lex.getLangOpts()) {
935 Lex.SetKeepWhitespaceMode(true);
936 }
937
938 virtual FormatToken getNextToken() {
939 if (GreaterStashed) {
940 FormatTok.NewlinesBefore = 0;
941 FormatTok.WhiteSpaceStart =
942 FormatTok.Tok.getLocation().getLocWithOffset(1);
943 FormatTok.WhiteSpaceLength = 0;
944 GreaterStashed = false;
945 return FormatTok;
946 }
947
948 FormatTok = FormatToken();
949 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000950 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000951 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000952 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
953 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000954
955 // Consume and record whitespace until we find a significant token.
956 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000957 unsigned Newlines = Text.count('\n');
958 unsigned EscapedNewlines = Text.count("\\\n");
959 FormatTok.NewlinesBefore += Newlines;
960 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000961 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
962
963 if (FormatTok.Tok.is(tok::eof))
964 return FormatTok;
965 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000966 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000967 }
Manuel Klimek95419382013-01-07 07:56:50 +0000968
969 // Now FormatTok is the next non-whitespace token.
970 FormatTok.TokenLength = Text.size();
971
Manuel Klimekd4397b92013-01-04 23:34:14 +0000972 // In case the token starts with escaped newlines, we want to
973 // take them into account as whitespace - this pattern is quite frequent
974 // in macro definitions.
975 // FIXME: What do we want to do with other escaped spaces, and escaped
976 // spaces or newlines in the middle of tokens?
977 // FIXME: Add a more explicit test.
978 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000979 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000980 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000981 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000982 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000983 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000984 }
985
986 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000987 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000988 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000989 FormatTok.Tok.setKind(Info.getTokenID());
990 }
991
992 if (FormatTok.Tok.is(tok::greatergreater)) {
993 FormatTok.Tok.setKind(tok::greater);
994 GreaterStashed = true;
995 }
996
997 return FormatTok;
998 }
999
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001000 IdentifierTable &getIdentTable() { return IdentTable; }
1001
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001002private:
1003 FormatToken FormatTok;
1004 bool GreaterStashed;
1005 Lexer &Lex;
1006 SourceManager &SourceMgr;
1007 IdentifierTable IdentTable;
1008
1009 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001010 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001011 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1012 Tok.getLength());
1013 }
1014};
1015
Daniel Jasperbac016b2012-12-03 18:12:45 +00001016class Formatter : public UnwrappedLineConsumer {
1017public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001018 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1019 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001020 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001021 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001022 Whitespaces(SourceMgr), Ranges(Ranges) {
1023 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001024
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001025 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001026
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001027 void deriveLocalStyle() {
1028 unsigned CountBoundToVariable = 0;
1029 unsigned CountBoundToType = 0;
1030 bool HasCpp03IncompatibleFormat = false;
1031 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1032 if (AnnotatedLines[i].First.Children.empty())
1033 continue;
1034 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1035 while (!Tok->Children.empty()) {
1036 if (Tok->Type == TT_PointerOrReference) {
1037 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1038 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1039 if (SpacesBefore && !SpacesAfter)
1040 ++CountBoundToVariable;
1041 else if (!SpacesBefore && SpacesAfter)
1042 ++CountBoundToType;
1043 }
1044
Daniel Jasper29f123b2013-02-08 15:28:42 +00001045 if (Tok->Type == TT_TemplateCloser &&
1046 Tok->Parent->Type == TT_TemplateCloser &&
1047 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001048 HasCpp03IncompatibleFormat = true;
1049 Tok = &Tok->Children[0];
1050 }
1051 }
1052 if (Style.DerivePointerBinding) {
1053 if (CountBoundToType > CountBoundToVariable)
1054 Style.PointerBindsToType = true;
1055 else if (CountBoundToType < CountBoundToVariable)
1056 Style.PointerBindsToType = false;
1057 }
1058 if (Style.Standard == FormatStyle::LS_Auto) {
1059 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1060 : FormatStyle::LS_Cpp03;
1061 }
1062 }
1063
Daniel Jasperbac016b2012-12-03 18:12:45 +00001064 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001065 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001066 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001067 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001068 unsigned PreviousEndOfLineColumn = 0;
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001069 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1070 Tokens.getIdentTable().get("in"));
Daniel Jasper995e8202013-01-14 13:08:07 +00001071 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001072 Annotator.annotate(AnnotatedLines[i]);
1073 }
1074 deriveLocalStyle();
1075 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1076 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +00001077 }
Manuel Klimek547d5db2013-02-08 17:38:27 +00001078 std::vector<int> IndentForLevel;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001079 bool PreviousLineWasTouched = false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001080 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1081 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001082 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001083 const AnnotatedLine &TheLine = *I;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001084 int Offset = getIndentOffset(TheLine.First);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001085 while (IndentForLevel.size() <= TheLine.Level)
1086 IndentForLevel.push_back(-1);
1087 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper29333162013-02-18 13:08:03 +00001088 bool WasMoved =
1089 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
1090 if (TheLine.Type != LT_Invalid && (WasMoved || touchesRanges(TheLine))) {
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001091 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001092 unsigned Indent = LevelIndent;
1093 if (static_cast<int>(Indent) + Offset >= 0)
1094 Indent += Offset;
1095 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1096 StructuralError) {
1097 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1098 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1099 } else {
1100 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1101 PreviousEndOfLineColumn);
1102 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001103 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001104 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001105 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001106 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001107 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimek547d5db2013-02-08 17:38:27 +00001108 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001109 PreviousLineWasTouched = true;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001110 } else {
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001111 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1112 TheLine.First.FormatTok.IsFirst) {
1113 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1114 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1115 unsigned LevelIndent = Indent;
1116 if (static_cast<int>(LevelIndent) - Offset >= 0)
1117 LevelIndent -= Offset;
1118 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001119
1120 // Remove trailing whitespace of the previous line if it was touched.
1121 if (PreviousLineWasTouched)
1122 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1123 PreviousEndOfLineColumn);
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001124 }
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001125 // If we did not reformat this unwrapped line, the column at the end of
1126 // the last token is unchanged - thus, we can calculate the end of the
1127 // last token.
1128 PreviousEndOfLineColumn =
1129 SourceMgr.getSpellingColumnNumber(
1130 TheLine.Last->FormatTok.Tok.getLocation()) +
1131 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1132 SourceMgr, Lex.getLangOpts()) - 1;
1133 PreviousLineWasTouched = false;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001134 }
1135 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001136 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001137 }
1138
1139private:
Manuel Klimek547d5db2013-02-08 17:38:27 +00001140 /// \brief Get the indent of \p Level from \p IndentForLevel.
1141 ///
1142 /// \p IndentForLevel must contain the indent for the level \c l
1143 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1144 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001145 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001146 if (IndentForLevel[Level] != -1)
1147 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001148 if (Level == 0)
1149 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001150 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001151 }
1152
1153 /// \brief Get the offset of the line relatively to the level.
1154 ///
1155 /// For example, 'public:' labels in classes are offset by 1 or 2
1156 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001157 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001158 bool IsAccessModifier = false;
1159 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1160 RootToken.is(tok::kw_private))
1161 IsAccessModifier = true;
1162 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1163 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1164 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1165 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1166 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1167 IsAccessModifier = true;
1168
1169 if (IsAccessModifier)
1170 return Style.AccessModifierOffset;
1171 return 0;
1172 }
1173
Manuel Klimek517e8942013-01-11 17:54:10 +00001174 /// \brief Tries to merge lines into one.
1175 ///
1176 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1177 /// if possible; note that \c I will be incremented when lines are merged.
1178 ///
1179 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001180 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001181 std::vector<AnnotatedLine>::iterator &I,
1182 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001183 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1184
Daniel Jasper3f8cdbf2013-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
Manuel Klimek517e8942013-01-11 17:54:10 +00001189 // Check whether the UnwrappedLine can be put onto a single line. If
1190 // so, this is bound to be the optimal solution (by definition) and we
1191 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001192 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001193 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001194 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001195
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001196 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001197 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001198
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001199 if (I->Last->is(tok::l_brace)) {
1200 tryMergeSimpleBlock(I, E, Limit);
1201 } else if (I->First.is(tok::kw_if)) {
1202 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001203 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1204 I->First.FormatTok.IsFirst)) {
1205 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001206 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001207 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001208 }
1209
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001210 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1211 std::vector<AnnotatedLine>::iterator E,
1212 unsigned Limit) {
1213 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001214 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1215 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001216 if (I + 2 != E && (I + 2)->InPPDirective &&
1217 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1218 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001219 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001220 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001221 join(Line, *(++I));
1222 }
1223
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001224 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1225 std::vector<AnnotatedLine>::iterator E,
1226 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001227 if (!Style.AllowShortIfStatementsOnASingleLine)
1228 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001229 if ((I + 1)->InPPDirective != I->InPPDirective ||
1230 ((I + 1)->InPPDirective &&
1231 (I + 1)->First.FormatTok.HasUnescapedNewline))
1232 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001233 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001234 if (Line.Last->isNot(tok::r_paren))
1235 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001236 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001237 return;
1238 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1239 return;
1240 // Only inline simple if's (no nested if or else).
1241 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1242 return;
1243 join(Line, *(++I));
1244 }
1245
1246 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001247 std::vector<AnnotatedLine>::iterator E,
1248 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001249 // First, check that the current line allows merging. This is the case if
1250 // we're not in a control flow statement and the last token is an opening
1251 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001252 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001253 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001254 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1255 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1256 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1257 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001258 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001259 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1260 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001261 if (!AllowedTokens)
1262 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001263
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001264 AnnotatedToken *Tok = &(I + 1)->First;
1265 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1266 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jasper729a7432013-02-11 12:36:37 +00001267 Tok->SpacesRequiredBefore = 0;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001268 join(Line, *(I + 1));
1269 I += 1;
1270 } else {
1271 // Check that we still have three lines and they fit into the limit.
1272 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1273 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001274 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001275
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001276 // Second, check that the next line does not contain any braces - if it
1277 // does, readability declines when putting it into a single line.
1278 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1279 return;
1280 do {
1281 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1282 return;
1283 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1284 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001285
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001286 // Last, check that the third line contains a single closing brace.
1287 Tok = &(I + 2)->First;
1288 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1289 Tok->MustBreakBefore)
1290 return;
1291
1292 join(Line, *(I + 1));
1293 join(Line, *(I + 2));
1294 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001295 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001296 }
1297
1298 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1299 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001300 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1301 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001302 }
1303
Daniel Jasper995e8202013-01-14 13:08:07 +00001304 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1305 A.Last->Children.push_back(B.First);
1306 while (!A.Last->Children.empty()) {
1307 A.Last->Children[0].Parent = A.Last;
1308 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