blob: b483308a5a4cdb86b8628293ad26db56d6084cf9 [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
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperbac016b2012-12-03 18:12:45 +000037FormatStyle getLLVMStyle() {
38 FormatStyle LLVMStyle;
39 LLVMStyle.ColumnLimit = 80;
40 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000041 LLVMStyle.PointerBindsToType = false;
42 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000043 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000044 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000045 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000046 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000047 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000048 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000049 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000050 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000051 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000052 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000053 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Daniel Jasperbac016b2012-12-03 18:12:45 +000054 return LLVMStyle;
55}
56
57FormatStyle getGoogleStyle() {
58 FormatStyle GoogleStyle;
59 GoogleStyle.ColumnLimit = 80;
60 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000061 GoogleStyle.PointerBindsToType = true;
62 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000063 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000064 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000065 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000066 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000067 GoogleStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000068 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000069 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper94d6ad72013-04-24 13:46:00 +000070 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Weber5f500df2013-01-10 20:12:55 +000071 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000072 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000073 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasperbac016b2012-12-03 18:12:45 +000074 return GoogleStyle;
75}
76
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000077FormatStyle getChromiumStyle() {
78 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000079 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper94d6ad72013-04-24 13:46:00 +000080 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000081 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000082 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
83 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000084 return ChromiumStyle;
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 Jasperbac016b2012-12-03 18:12:45 +000099class UnwrappedLineFormatter {
100public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000101 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000102 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000103 const AnnotatedToken &RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000104 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000105 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000106 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000107 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000108
Manuel Klimekd4397b92013-01-04 23:34:14 +0000109 /// \brief Formats an \c UnwrappedLine.
110 ///
111 /// \returns The column after the last token in the last line of the
112 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000113 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000114 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000115 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000116 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000117 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000118 State.Stack.push_back(
Daniel Jasper37911302013-04-02 14:33:13 +0000119 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000120 /*NoLineBreak=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000121 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000122 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000123 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000124 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000125
126 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000127 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000128
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000129 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000130 unsigned ColumnLimit = Style.ColumnLimit;
131 if (NextLine && NextLine->InPPDirective &&
132 !NextLine->First.FormatTok.HasUnescapedNewline)
133 ColumnLimit = getColumnLimit();
134 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000135 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000136 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000137 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000138 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000139 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000140
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000141 // If the ObjC method declaration does not fit on a line, we should format
142 // it with one arg per line.
143 if (Line.Type == LT_ObjCMethodDecl)
144 State.Stack.back().BreakBeforeParameter = true;
145
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000146 // Find best solution in solution space.
147 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000148 }
149
150private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000151 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
152 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000153 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
154 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000155 llvm::errs();
156 }
157
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000158 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000159 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000160 bool NoLineBreak)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000161 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
162 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000163 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000164 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
165 NestedNameSpecifierContinuation(0), CallContinuation(0),
166 VariablePos(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000167
Daniel Jasperbac016b2012-12-03 18:12:45 +0000168 /// \brief The position to which a specific parenthesis level needs to be
169 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000170 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000171
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000172 /// \brief The position of the last space on each level.
173 ///
174 /// Used e.g. to break like:
175 /// functionCall(Parameter, otherCall(
176 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000177 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000178
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000179 /// \brief The position the first "<<" operator encountered on each level.
180 ///
181 /// Used to align "<<" operators. 0 if no such operator has been encountered
182 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000183 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000184
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000185 /// \brief Whether a newline needs to be inserted before the block's closing
186 /// brace.
187 ///
188 /// We only want to insert a newline before the closing brace if there also
189 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000190 bool BreakBeforeClosingBrace;
191
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000192 /// \brief The column of a \c ? in a conditional expression;
193 unsigned QuestionColumn;
194
Daniel Jasperf343cab2013-01-31 14:59:26 +0000195 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
196 /// lines, in this context.
197 bool AvoidBinPacking;
198
199 /// \brief Break after the next comma (or all the commas in this context if
200 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000201 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000202
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000203 /// \brief Line breaking in this context would break a formatting rule.
204 bool NoLineBreak;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000205
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000206 /// \brief The position of the colon in an ObjC method declaration/call.
207 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000208
Daniel Jasper24849712013-03-01 16:48:32 +0000209 /// \brief The start of the most recent function in a builder-type call.
210 unsigned StartOfFunctionCall;
211
Daniel Jasper37911302013-04-02 14:33:13 +0000212 /// \brief If a nested name specifier was broken over multiple lines, this
213 /// contains the start column of the second line. Otherwise 0.
214 unsigned NestedNameSpecifierContinuation;
215
216 /// \brief If a call expression was broken over multiple lines, this
217 /// contains the start column of the second line. Otherwise 0.
218 unsigned CallContinuation;
219
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000220 /// \brief The column of the first variable name in a variable declaration.
221 ///
222 /// Used to align further variables if necessary.
223 unsigned VariablePos;
224
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000225 bool operator<(const ParenState &Other) const {
226 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000227 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000228 if (LastSpace != Other.LastSpace)
229 return LastSpace < Other.LastSpace;
230 if (FirstLessLess != Other.FirstLessLess)
231 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000232 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
233 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000234 if (QuestionColumn != Other.QuestionColumn)
235 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000236 if (AvoidBinPacking != Other.AvoidBinPacking)
237 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000238 if (BreakBeforeParameter != Other.BreakBeforeParameter)
239 return BreakBeforeParameter;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000240 if (NoLineBreak != Other.NoLineBreak)
241 return NoLineBreak;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000242 if (ColonPos != Other.ColonPos)
243 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000244 if (StartOfFunctionCall != Other.StartOfFunctionCall)
245 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000246 if (NestedNameSpecifierContinuation !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000247 Other.NestedNameSpecifierContinuation)
Daniel Jasper37911302013-04-02 14:33:13 +0000248 return NestedNameSpecifierContinuation <
249 Other.NestedNameSpecifierContinuation;
250 if (CallContinuation != Other.CallContinuation)
251 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000252 if (VariablePos != Other.VariablePos)
253 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000254 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000255 }
256 };
257
258 /// \brief The current state when indenting a unwrapped line.
259 ///
260 /// As the indenting tries different combinations this is copied by value.
261 struct LineState {
262 /// \brief The number of used columns in the current line.
263 unsigned Column;
264
265 /// \brief The token that needs to be next formatted.
266 const AnnotatedToken *NextToken;
267
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000268 /// \brief \c true if this line contains a continued for-loop section.
269 bool LineContainsContinuedForLoopSection;
270
Daniel Jasper29f123b2013-02-08 15:28:42 +0000271 /// \brief The level of nesting inside (), [], <> and {}.
272 unsigned ParenLevel;
273
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000274 /// \brief The \c ParenLevel at the start of this line.
275 unsigned StartOfLineLevel;
276
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000277 /// \brief The start column of the string literal, if we're in a string
278 /// literal sequence, 0 otherwise.
279 unsigned StartOfStringLiteral;
280
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000281 /// \brief A stack keeping track of properties applying to parenthesis
282 /// levels.
283 std::vector<ParenState> Stack;
284
285 /// \brief Comparison operator to be able to used \c LineState in \c map.
286 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000287 if (NextToken != Other.NextToken)
288 return NextToken < Other.NextToken;
289 if (Column != Other.Column)
290 return Column < Other.Column;
Daniel Jasperd7896702013-02-19 09:28:55 +0000291 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000292 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000293 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000294 if (ParenLevel != Other.ParenLevel)
295 return ParenLevel < Other.ParenLevel;
296 if (StartOfLineLevel != Other.StartOfLineLevel)
297 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000298 if (StartOfStringLiteral != Other.StartOfStringLiteral)
299 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000300 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000301 }
302 };
303
Daniel Jasper20409152012-12-04 14:54:30 +0000304 /// \brief Appends the next token to \p State and updates information
305 /// necessary for indentation.
306 ///
307 /// Puts the token on the current line if \p Newline is \c true and adds a
308 /// line break and necessary indentation otherwise.
309 ///
310 /// If \p DryRun is \c false, also creates and stores the required
311 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000312 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000313 const AnnotatedToken &Current = *State.NextToken;
314 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000315
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000316 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000317 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
318 State.NextToken->FormatTok.TokenLength;
319 if (State.NextToken->Children.empty())
320 State.NextToken = NULL;
321 else
322 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000323 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000324 }
325
Daniel Jasper3776ef32013-04-03 07:21:51 +0000326 // If we are continuing an expression, we want to indent an extra 4 spaces.
327 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000328 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000330 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000331 if (Current.is(tok::r_brace)) {
332 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000333 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000334 State.StartOfStringLiteral != 0) {
335 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000336 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000337 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000338 State.Stack.back().FirstLessLess != 0) {
339 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper37911302013-04-02 14:33:13 +0000340 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000341 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
342 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000343 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000344 } else {
345 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
346 }
Daniel Jasper37911302013-04-02 14:33:13 +0000347 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000348 if (State.Stack.back().CallContinuation == 0) {
349 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000350 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000351 } else {
352 State.Column = State.Stack.back().CallContinuation;
353 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000354 } else if (Current.Type == TT_ConditionalExpr) {
355 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000356 } else if (Previous.is(tok::comma) &&
357 State.Stack.back().VariablePos != 0) {
358 State.Column = State.Stack.back().VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000359 } else if (Previous.ClosesTemplateDeclaration ||
360 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000361 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000362 } else if (Current.Type == TT_ObjCSelectorName) {
363 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
364 State.Column =
365 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
366 } else {
367 State.Column = State.Stack.back().Indent;
368 State.Stack.back().ColonPos =
369 State.Column + Current.FormatTok.TokenLength;
370 }
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000371 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000372 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000373 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000374 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000375 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000376 // Ensure that we fall back to indenting 4 spaces instead of just
377 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000378 if (State.Column == FirstIndent)
379 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000380 }
381
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000382 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000383 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000384 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jasper237d4c12013-02-23 21:01:55 +0000385 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000386 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000387
Manuel Klimek060143e2013-01-02 18:33:23 +0000388 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000389 unsigned NewLines = 1;
390 if (Current.Type == TT_LineComment)
391 NewLines =
392 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
393 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000394 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000395 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000396 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000397 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000398 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000399 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000400 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000401
Daniel Jasper29f123b2013-02-08 15:28:42 +0000402 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000403 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000404
405 // Any break on this level means that the parent level has been broken
406 // and we need to avoid bin packing there.
407 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
408 State.Stack[i].BreakBeforeParameter = true;
409 }
Daniel Jasper01218ff2013-04-15 22:36:37 +0000410 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
411 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
412 !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000413 State.Stack.back().BreakBeforeParameter = true;
414
Daniel Jasper237d4c12013-02-23 21:01:55 +0000415 // If we break after {, we should also break before the corresponding }.
416 if (Previous.is(tok::l_brace))
417 State.Stack.back().BreakBeforeClosingBrace = true;
418
419 if (State.Stack.back().AvoidBinPacking) {
420 // If we are breaking after '(', '{', '<', this is not bin packing
421 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000422 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000423 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
424 Line.MustBeDeclaration))
425 State.Stack.back().BreakBeforeParameter = true;
426 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000427 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000428 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000429 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
430 State.Stack.back().VariablePos == 0) {
431 State.Stack.back().VariablePos = State.Column;
432 // Move over * and & if they are bound to the variable name.
433 const AnnotatedToken *Tok = &Previous;
434 while (Tok &&
435 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
436 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
437 if (Tok->SpacesRequiredBefore != 0)
438 break;
439 Tok = Tok->Parent;
440 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000441 if (Previous.PartOfMultiVariableDeclStmt)
442 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
443 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000444
Daniel Jasper729a7432013-02-11 12:36:37 +0000445 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000446
Daniel Jasperbac016b2012-12-03 18:12:45 +0000447 if (!DryRun)
Alexander Kornienko052685c2013-03-19 17:41:36 +0000448 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper20409152012-12-04 14:54:30 +0000449
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000450 if (Current.Type == TT_ObjCSelectorName &&
451 State.Stack.back().ColonPos == 0) {
452 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000453 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000454 State.Stack.back().ColonPos =
455 State.Stack.back().Indent + Current.LongestObjCSelectorName;
456 else
457 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000458 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000459 }
460
Daniel Jasperac3223e2013-04-10 09:49:49 +0000461 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000462 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000463 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000464 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
465 State.Stack.back().AvoidBinPacking)
466 State.Stack.back().NoLineBreak = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000467
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000468 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000469 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000470 // Treat the condition inside an if as if it was a second function
471 // parameter, i.e. let nested calls have an indent of 4.
472 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000473 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000474 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000475 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000476 Previous.Type == TT_ConditionalExpr ||
477 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000478 getPrecedence(Previous) != prec::Assignment)
479 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000480 else if (Previous.Type == TT_InheritanceColon)
481 State.Stack.back().Indent = State.Column;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000482 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper986e17f2013-01-28 07:35:34 +0000483 // If this function has multiple parameters, indent nested calls from
484 // the start of the first parameter.
485 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000486 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000487
Manuel Klimek8092a942013-02-20 10:15:13 +0000488 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000489 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000490
Daniel Jasper20409152012-12-04 14:54:30 +0000491 /// \brief Mark the next token as consumed in \p State and modify its stacks
492 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000493 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000494 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000495 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000496
Daniel Jasper6cabab42013-02-14 08:42:54 +0000497 if (Current.Type == TT_InheritanceColon)
498 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000499 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
500 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000501 if (Current.is(tok::question))
502 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000503 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000504 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
505 State.Stack.back().StartOfFunctionCall =
506 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000507 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000508 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000509 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
510 State.Stack.back().AvoidBinPacking = true;
511 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000512 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000513
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000514 // If return returns a binary expression, align after it.
515 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
516 State.Stack.back().LastSpace = State.Column + 7;
517
Daniel Jasper3776ef32013-04-03 07:21:51 +0000518 // In ObjC method declaration we align on the ":" of parameters, but we need
519 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000520 if (Current.Type == TT_ObjCMethodSpecifier)
521 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000522
Daniel Jasper29f123b2013-02-08 15:28:42 +0000523 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000524 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
525 // Don't add extra indentation for the first fake parenthesis after
526 // 'return', assignements or opening <({[. The indentation for these cases
527 // is special cased.
528 bool SkipFirstExtraIndent =
529 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000530 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000531 getPrecedence(*Previous) == prec::Assignment));
532 for (SmallVector<prec::Level, 4>::const_reverse_iterator
533 I = Current.FakeLParens.rbegin(),
534 E = Current.FakeLParens.rend();
535 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000536 ParenState NewParenState = State.Stack.back();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000537 NewParenState.Indent =
538 std::max(std::max(State.Column, NewParenState.Indent),
539 State.Stack.back().LastSpace);
540
541 // Always indent conditional expressions. Never indent expression where
542 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
543 // prec::Assignment) as those have different indentation rules. Indent
544 // other expression, unless the indentation needs to be skipped.
545 if (*I == prec::Conditional ||
546 (!SkipFirstExtraIndent && *I > prec::Assignment))
547 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000548 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000549 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000550 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000551 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000552 }
553
Daniel Jaspercf225b62012-12-24 13:43:52 +0000554 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000555 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000556 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000557 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000558 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000559 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000560 NewIndent = 2 + State.Stack.back().LastSpace;
561 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000562 } else {
Daniel Jasper24849712013-03-01 16:48:32 +0000563 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
564 State.Stack.back().StartOfFunctionCall);
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000565 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000566 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000567 State.Stack.push_back(
568 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000569 State.Stack.back().NoLineBreak));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000570 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000571 }
572
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000573 // If this '[' opens an ObjC call, determine whether all parameters fit into
574 // one line and put one per line if they don't.
575 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
576 Current.MatchingParen != NULL) {
577 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
578 State.Stack.back().BreakBeforeParameter = true;
579 }
580
Daniel Jaspercf225b62012-12-24 13:43:52 +0000581 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000582 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000583 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000584 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
585 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000586 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000587 --State.ParenLevel;
588 }
589
590 // Remove scopes created by fake parenthesis.
591 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000592 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000593 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000594 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000595 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000596
Manuel Klimeke9a62262013-02-20 15:32:58 +0000597 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000598 State.StartOfStringLiteral = State.Column;
599 } else if (Current.isNot(tok::comment)) {
600 State.StartOfStringLiteral = 0;
601 }
602
Manuel Klimek8092a942013-02-20 10:15:13 +0000603 State.Column += Current.FormatTok.TokenLength;
604
Daniel Jasper26f7e782013-01-08 14:56:18 +0000605 if (State.NextToken->Children.empty())
606 State.NextToken = NULL;
607 else
608 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000609
Manuel Klimek8092a942013-02-20 10:15:13 +0000610 return breakProtrudingToken(Current, State, DryRun);
611 }
612
613 /// \brief If the current token sticks out over the end of the line, break
614 /// it if possible.
615 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
616 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000617 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek8092a942013-02-20 10:15:13 +0000618 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000619 if (Current.is(tok::string_literal)) {
620 // Only break up default narrow strings.
Alexander Kornienko919398b2013-04-17 17:34:05 +0000621 const char *LiteralData = SourceMgr.getCharacterData(
622 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000623 if (!LiteralData || *LiteralData != '"')
624 return 0;
625
Alexander Kornienko919398b2013-04-17 17:34:05 +0000626 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
627 StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000628 } else if (Current.Type == TT_BlockComment) {
629 BreakableBlockComment *BBC =
630 new BreakableBlockComment(SourceMgr, Current, StartColumn);
631 if (!DryRun)
632 BBC->alignLines(Whitespaces);
633 Token.reset(BBC);
Alexander Kornienko919398b2013-04-17 17:34:05 +0000634 } else if (Current.Type == TT_LineComment) {
635 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000636 } else {
637 return 0;
638 }
639
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000640 bool BreakInserted = false;
641 unsigned Penalty = 0;
642 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
643 ++LineIndex) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000644 unsigned TailOffset = 0;
645 unsigned RemainingLength =
646 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
647 while (RemainingLength > getColumnLimit()) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000648 BreakableToken::Split Split =
649 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
650 if (Split.first == StringRef::npos)
651 break;
652 assert(Split.first != 0);
Alexander Kornienko919398b2013-04-17 17:34:05 +0000653 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
654 LineIndex, TailOffset + Split.first + Split.second);
655 if (NewRemainingLength >= RemainingLength)
656 break;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000657 if (!DryRun) {
658 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
659 Whitespaces);
660 }
661 TailOffset += Split.first + Split.second;
Alexander Kornienkoe2657dd2013-04-15 15:47:34 +0000662 RemainingLength = NewRemainingLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000663 Penalty += Style.PenaltyExcessCharacter;
664 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000665 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000666 State.Column = RemainingLength;
667 if (!DryRun) {
668 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
669 }
670 }
671
672 if (BreakInserted) {
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000673 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
674 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000675 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000676 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000677 return Penalty;
678 }
679
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000680 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000681 // In preprocessor directives reserve two chars for trailing " \"
682 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000683 }
684
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000685 /// \brief An edge in the solution space from \c Previous->State to \c State,
686 /// inserting a newline dependent on the \c NewLine.
687 struct StateNode {
688 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000689 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000690 LineState State;
691 bool NewLine;
692 StateNode *Previous;
693 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000694
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000695 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
696 ///
697 /// In case of equal penalties, we want to prefer states that were inserted
698 /// first. During state generation we make sure that we insert states first
699 /// that break the line as late as possible.
700 typedef std::pair<unsigned, unsigned> OrderedPenalty;
701
702 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
703 /// \c State has the given \c OrderedPenalty.
704 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
705
706 /// \brief The BFS queue type.
707 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
708 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000709
710 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000711 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000712 /// This implements a variant of Dijkstra's algorithm on the graph that spans
713 /// the solution space (\c LineStates are the nodes). The algorithm tries to
714 /// find the shortest path (the one with lowest penalty) from \p InitialState
715 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000716 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000717 std::set<LineState> Seen;
718
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000719 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000720 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000721 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
722 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
723 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000724
725 // While not empty, take first element and follow edges.
726 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000727 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000728 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000729 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000730 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000731 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000732 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000733 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000734
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000735 if (!Seen.insert(Node->State).second)
736 // State already examined with lower penalty.
737 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000738
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000739 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
740 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000741 }
742
743 if (Queue.empty())
744 // We were unable to find a solution, do nothing.
745 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000746 return 0;
747
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000748 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000749 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000750 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000751
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000752 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000753 return Queue.top().second->State.Column;
754 }
755
756 void reconstructPath(LineState &State, StateNode *Current) {
757 // FIXME: This recursive implementation limits the possible number
758 // of tokens per line if compiled into a binary with small stack space.
759 // To become more independent of stack frame limitations we would need
760 // to also change the TokenAnnotator.
761 if (Current->Previous == NULL)
762 return;
763 reconstructPath(State, Current->Previous);
764 DEBUG({
765 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000766 llvm::errs()
767 << "Penalty for splitting before "
768 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
769 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000770 }
771 });
772 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000773 }
774
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000775 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000776 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000777 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000778 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000779 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
780 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000781 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000782 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000783 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000784 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000785 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000786 Penalty += PreviousNode->State.NextToken->SplitPenalty;
787
788 StateNode *Node = new (Allocator.Allocate())
789 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000790 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000791 if (Node->State.Column > getColumnLimit()) {
792 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000793 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000794 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000795
796 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
797 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000798 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000799
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000800 /// \brief Returns \c true, if a line break after \p State is allowed.
801 bool canBreak(const LineState &State) {
802 if (!State.NextToken->CanBreakBefore &&
803 !(State.NextToken->is(tok::r_brace) &&
804 State.Stack.back().BreakBeforeClosingBrace))
805 return false;
Daniel Jasper001bf4e2013-04-22 07:59:53 +0000806 return !State.Stack.back().NoLineBreak;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000807 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000808
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000809 /// \brief Returns \c true, if a line break after \p State is mandatory.
810 bool mustBreak(const LineState &State) {
811 if (State.NextToken->MustBreakBefore)
812 return true;
813 if (State.NextToken->is(tok::r_brace) &&
814 State.Stack.back().BreakBeforeClosingBrace)
815 return true;
816 if (State.NextToken->Parent->is(tok::semi) &&
817 State.LineContainsContinuedForLoopSection)
818 return true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000819 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000820 State.NextToken->is(tok::question) ||
821 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000822 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperac3223e2013-04-10 09:49:49 +0000823 !State.NextToken->isTrailingComment() &&
Daniel Jasper7d812812013-02-21 15:00:29 +0000824 State.NextToken->isNot(tok::r_paren) &&
825 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000826 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000827 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
828 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000829 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000830 State.NextToken->LongestObjCSelectorName == 0 &&
831 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000832 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000833 if ((State.NextToken->Type == TT_CtorInitializerColon ||
834 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000835 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000836 return true;
Daniel Jasper923ebef2013-03-14 13:45:21 +0000837 if (State.NextToken->Type == TT_InlineASMColon)
838 return true;
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000839 // This prevents breaks like:
840 // ...
841 // SomeParameter, OtherParameter).DoSomething(
842 // ...
843 // As they hide "DoSomething" and generally bad for readability.
844 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
845 getRemainingLength(State) + State.Column > getColumnLimit() &&
846 State.ParenLevel < State.StartOfLineLevel)
847 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000848 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000849 }
850
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000851 // Returns the total number of columns required for the remaining tokens.
852 unsigned getRemainingLength(const LineState &State) {
853 if (State.NextToken && State.NextToken->Parent)
854 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
855 return 0;
856 }
857
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858 FormatStyle Style;
859 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000860 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000861 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000862 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000863 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000864
865 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
866 QueueType Queue;
867 // Increasing count of \c StateNode items we have created. This is used
868 // to create a deterministic order independent of the container.
869 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000870};
871
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000872class LexerBasedFormatTokenSource : public FormatTokenSource {
873public:
874 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000875 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000876 IdentTable(Lex.getLangOpts()) {
877 Lex.SetKeepWhitespaceMode(true);
878 }
879
880 virtual FormatToken getNextToken() {
881 if (GreaterStashed) {
882 FormatTok.NewlinesBefore = 0;
883 FormatTok.WhiteSpaceStart =
884 FormatTok.Tok.getLocation().getLocWithOffset(1);
885 FormatTok.WhiteSpaceLength = 0;
886 GreaterStashed = false;
887 return FormatTok;
888 }
889
890 FormatTok = FormatToken();
891 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000892 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000893 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000894 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
895 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000896
897 // Consume and record whitespace until we find a significant token.
898 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000899 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +0000900 if (Newlines > 0)
901 FormatTok.LastNewlineOffset =
902 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +0000903 unsigned EscapedNewlines = Text.count("\\\n");
904 FormatTok.NewlinesBefore += Newlines;
905 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000906 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
907
908 if (FormatTok.Tok.is(tok::eof))
909 return FormatTok;
910 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000911 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000912 }
Manuel Klimek95419382013-01-07 07:56:50 +0000913
914 // Now FormatTok is the next non-whitespace token.
915 FormatTok.TokenLength = Text.size();
916
Alexander Kornienko919398b2013-04-17 17:34:05 +0000917 if (FormatTok.Tok.is(tok::comment)) {
918 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
919 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
920 }
921
Manuel Klimekd4397b92013-01-04 23:34:14 +0000922 // In case the token starts with escaped newlines, we want to
923 // take them into account as whitespace - this pattern is quite frequent
924 // in macro definitions.
925 // FIXME: What do we want to do with other escaped spaces, and escaped
926 // spaces or newlines in the middle of tokens?
927 // FIXME: Add a more explicit test.
928 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000929 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000930 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000931 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000932 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000933 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000934 }
935
936 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000937 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000938 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000939 FormatTok.Tok.setKind(Info.getTokenID());
940 }
941
942 if (FormatTok.Tok.is(tok::greatergreater)) {
943 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +0000944 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000945 GreaterStashed = true;
946 }
947
948 return FormatTok;
949 }
950
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000951 IdentifierTable &getIdentTable() { return IdentTable; }
952
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000953private:
954 FormatToken FormatTok;
955 bool GreaterStashed;
956 Lexer &Lex;
957 SourceManager &SourceMgr;
958 IdentifierTable IdentTable;
959
960 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000961 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000962 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
963 Tok.getLength());
964 }
965};
966
Daniel Jasperbac016b2012-12-03 18:12:45 +0000967class Formatter : public UnwrappedLineConsumer {
968public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000969 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
970 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000971 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000972 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +0000973 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000974
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000975 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000976
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000977 tooling::Replacements format() {
978 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
979 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000980 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000981 unsigned PreviousEndOfLineColumn = 0;
982 TokenAnnotator Annotator(Style, SourceMgr, Lex,
983 Tokens.getIdentTable().get("in"));
984 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
985 Annotator.annotate(AnnotatedLines[i]);
986 }
987 deriveLocalStyle();
988 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
989 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
990 }
Daniel Jasper5999f762013-04-09 17:46:55 +0000991
992 // Adapt level to the next line if this is a comment.
993 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +0000994 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +0000995 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
996 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
997 AnnotatedLines[i].First.Children.empty())
998 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
999 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001000 NextNoneCommentLine =
1001 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1002 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001003 }
1004
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001005 std::vector<int> IndentForLevel;
1006 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001007 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001008 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1009 E = AnnotatedLines.end();
1010 I != E; ++I) {
1011 const AnnotatedLine &TheLine = *I;
1012 const FormatToken &FirstTok = TheLine.First.FormatTok;
1013 int Offset = getIndentOffset(TheLine.First);
1014 while (IndentForLevel.size() <= TheLine.Level)
1015 IndentForLevel.push_back(-1);
1016 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf9955d32013-03-20 12:37:50 +00001017 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001018 if (TheLine.First.is(tok::eof)) {
1019 if (PreviousLineWasTouched) {
1020 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1021 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001022 /*WhitespaceStartColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001023 }
1024 } else if (TheLine.Type != LT_Invalid &&
1025 (WasMoved || touchesLine(TheLine))) {
1026 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1027 unsigned Indent = LevelIndent;
1028 if (static_cast<int>(Indent) + Offset >= 0)
1029 Indent += Offset;
Manuel Klimek67d080d2013-04-12 14:13:36 +00001030 if (FirstTok.WhiteSpaceStart.isValid() &&
1031 // Insert a break even if there is a structural error in case where
1032 // we break apart a line consisting of multiple unwrapped lines.
1033 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001034 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1035 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001036 } else {
1037 Indent = LevelIndent =
1038 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001039 }
1040 tryFitMultipleLinesInOne(Indent, I, E);
1041 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001042 TheLine.First, Whitespaces);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001043 PreviousEndOfLineColumn =
1044 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1045 IndentForLevel[TheLine.Level] = LevelIndent;
1046 PreviousLineWasTouched = true;
1047 } else {
1048 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1049 unsigned Indent =
1050 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1051 unsigned LevelIndent = Indent;
1052 if (static_cast<int>(LevelIndent) - Offset >= 0)
1053 LevelIndent -= Offset;
Daniel Jasper83a90e52013-03-20 14:31:47 +00001054 if (TheLine.First.isNot(tok::comment))
1055 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001056
1057 // Remove trailing whitespace of the previous line if it was touched.
1058 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001059 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1060 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001061 }
1062 // If we did not reformat this unwrapped line, the column at the end of
1063 // the last token is unchanged - thus, we can calculate the end of the
1064 // last token.
1065 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1066 PreviousEndOfLineColumn =
1067 SourceMgr.getSpellingColumnNumber(LastLoc) +
1068 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1069 PreviousLineWasTouched = false;
Daniel Jasperc363dbb2013-03-22 16:25:51 +00001070 if (TheLine.Last->is(tok::comment))
1071 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1072 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Daniel Jasperaf849762013-04-24 06:33:59 +00001073 else
1074 Whitespaces.alignComments();
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001075 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001076 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001077 }
1078 return Whitespaces.generateReplacements();
1079 }
1080
1081private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001082 void deriveLocalStyle() {
1083 unsigned CountBoundToVariable = 0;
1084 unsigned CountBoundToType = 0;
1085 bool HasCpp03IncompatibleFormat = false;
1086 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1087 if (AnnotatedLines[i].First.Children.empty())
1088 continue;
1089 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1090 while (!Tok->Children.empty()) {
1091 if (Tok->Type == TT_PointerOrReference) {
1092 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1093 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1094 if (SpacesBefore && !SpacesAfter)
1095 ++CountBoundToVariable;
1096 else if (!SpacesBefore && SpacesAfter)
1097 ++CountBoundToType;
1098 }
1099
Daniel Jasper29f123b2013-02-08 15:28:42 +00001100 if (Tok->Type == TT_TemplateCloser &&
1101 Tok->Parent->Type == TT_TemplateCloser &&
1102 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001103 HasCpp03IncompatibleFormat = true;
1104 Tok = &Tok->Children[0];
1105 }
1106 }
1107 if (Style.DerivePointerBinding) {
1108 if (CountBoundToType > CountBoundToVariable)
1109 Style.PointerBindsToType = true;
1110 else if (CountBoundToType < CountBoundToVariable)
1111 Style.PointerBindsToType = false;
1112 }
1113 if (Style.Standard == FormatStyle::LS_Auto) {
1114 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1115 : FormatStyle::LS_Cpp03;
1116 }
1117 }
1118
Manuel Klimek547d5db2013-02-08 17:38:27 +00001119 /// \brief Get the indent of \p Level from \p IndentForLevel.
1120 ///
1121 /// \p IndentForLevel must contain the indent for the level \c l
1122 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1123 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001124 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001125 if (IndentForLevel[Level] != -1)
1126 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001127 if (Level == 0)
1128 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001129 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001130 }
1131
1132 /// \brief Get the offset of the line relatively to the level.
1133 ///
1134 /// For example, 'public:' labels in classes are offset by 1 or 2
1135 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001136 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001137 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001138 return Style.AccessModifierOffset;
1139 return 0;
1140 }
1141
Manuel Klimek517e8942013-01-11 17:54:10 +00001142 /// \brief Tries to merge lines into one.
1143 ///
1144 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1145 /// if possible; note that \c I will be incremented when lines are merged.
1146 ///
1147 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001148 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001149 std::vector<AnnotatedLine>::iterator &I,
1150 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001151 // We can never merge stuff if there are trailing line comments.
1152 if (I->Last->Type == TT_LineComment)
1153 return;
1154
Daniel Jaspera4d46212013-02-28 11:05:57 +00001155 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001156 // If we already exceed the column limit, we set 'Limit' to 0. The different
1157 // tryMerge..() functions can then decide whether to still do merging.
1158 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001159
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001160 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001161 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001162
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001163 if (I->Last->is(tok::l_brace)) {
1164 tryMergeSimpleBlock(I, E, Limit);
1165 } else if (I->First.is(tok::kw_if)) {
1166 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001167 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1168 I->First.FormatTok.IsFirst)) {
1169 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001170 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001171 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001172 }
1173
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001174 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1175 std::vector<AnnotatedLine>::iterator E,
1176 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001177 if (Limit == 0)
1178 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001179 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001180 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1181 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001182 if (I + 2 != E && (I + 2)->InPPDirective &&
1183 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1184 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001185 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001186 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001187 join(Line, *(++I));
1188 }
1189
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001190 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1191 std::vector<AnnotatedLine>::iterator E,
1192 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001193 if (Limit == 0)
1194 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001195 if (!Style.AllowShortIfStatementsOnASingleLine)
1196 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001197 if ((I + 1)->InPPDirective != I->InPPDirective ||
1198 ((I + 1)->InPPDirective &&
1199 (I + 1)->First.FormatTok.HasUnescapedNewline))
1200 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001201 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001202 if (Line.Last->isNot(tok::r_paren))
1203 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001204 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001205 return;
1206 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1207 return;
1208 // Only inline simple if's (no nested if or else).
1209 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1210 return;
1211 join(Line, *(++I));
1212 }
1213
1214 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001215 std::vector<AnnotatedLine>::iterator E,
1216 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001217 // First, check that the current line allows merging. This is the case if
1218 // we're not in a control flow statement and the last token is an opening
1219 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001220 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001221 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1222 tok::kw_else, tok::kw_try, tok::kw_catch,
1223 tok::kw_for,
1224 // This gets rid of all ObjC @ keywords and methods.
1225 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001226 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001227
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001228 AnnotatedToken *Tok = &(I + 1)->First;
1229 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001230 !Tok->MustBreakBefore) {
1231 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001232 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001233 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001234 join(Line, *(I + 1));
1235 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001236 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001237 // Check that we still have three lines and they fit into the limit.
1238 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1239 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001240 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001241
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001242 // Second, check that the next line does not contain any braces - if it
1243 // does, readability declines when putting it into a single line.
1244 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1245 return;
1246 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001247 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001248 return;
1249 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1250 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001251
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001252 // Last, check that the third line contains a single closing brace.
1253 Tok = &(I + 2)->First;
1254 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1255 Tok->MustBreakBefore)
1256 return;
1257
1258 join(Line, *(I + 1));
1259 join(Line, *(I + 2));
1260 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001261 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001262 }
1263
1264 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1265 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001266 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1267 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001268 }
1269
Daniel Jasper995e8202013-01-14 13:08:07 +00001270 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001271 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001272 A.Last->Children.push_back(B.First);
1273 while (!A.Last->Children.empty()) {
1274 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001275 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001276 A.Last = &A.Last->Children[0];
1277 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001278 }
1279
Daniel Jasper6f21a982013-03-13 07:49:51 +00001280 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001281 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1282 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1283 Ranges[i].getBegin()) &&
1284 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1285 Range.getBegin()))
1286 return true;
1287 }
1288 return false;
1289 }
1290
1291 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001292 const FormatToken *First = &TheLine.First.FormatTok;
1293 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001294 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001295 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1296 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001297 return touchesRanges(LineRange);
1298 }
1299
1300 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1301 const FormatToken *First = &TheLine.First.FormatTok;
1302 CharSourceRange LineRange = CharSourceRange::getCharRange(
1303 First->WhiteSpaceStart,
1304 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1305 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001306 }
1307
1308 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001309 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001310 }
1311
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001312 /// \brief Add a new line and the required indent before the first Token
1313 /// of the \c UnwrappedLine if there was no structural parsing error.
1314 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001315 void formatFirstToken(const AnnotatedToken &RootToken,
1316 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimek547d5db2013-02-08 17:38:27 +00001317 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001318 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001319
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001320 unsigned Newlines =
1321 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001322 if (Newlines == 0 && !Tok.IsFirst)
1323 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001324
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001325 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001326 // Insert extra new line before access specifiers.
1327 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1328 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1329 ++Newlines;
1330
Alexander Kornienko052685c2013-03-19 17:41:36 +00001331 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001332 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001333 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001334 PreviousEndOfLineColumn);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001335 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001336 }
1337
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001338 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001339 FormatStyle Style;
1340 Lexer &Lex;
1341 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001342 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001343 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001344 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001345};
1346
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001347tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1348 SourceManager &SourceMgr,
1349 std::vector<CharSourceRange> Ranges,
1350 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001351 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001352 OwningPtr<DiagnosticConsumer> DiagPrinter;
1353 if (DiagClient == 0) {
1354 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1355 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1356 DiagClient = DiagPrinter.get();
1357 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001358 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001359 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001360 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001361 Diagnostics.setSourceManager(&SourceMgr);
1362 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001363 return formatter.format();
1364}
1365
Daniel Jasper46ef8522013-01-10 13:08:12 +00001366LangOptions getFormattingLangOpts() {
1367 LangOptions LangOpts;
1368 LangOpts.CPlusPlus = 1;
1369 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001370 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001371 LangOpts.Bool = 1;
1372 LangOpts.ObjC1 = 1;
1373 LangOpts.ObjC2 = 1;
1374 return LangOpts;
1375}
1376
Daniel Jaspercd162382013-01-07 13:26:07 +00001377} // namespace format
1378} // namespace clang