blob: 5c064a6df9ea68c24f66168fcca0902f68458266 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimek24998102013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper7a6d09b2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienkocb45bc12013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienkoffd6d042013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimek24998102013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Manuel Klimek2ef908e2013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8b529712012-12-04 13:02:32 +000032#include <string>
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperf7935112012-12-03 18:12:45 +000037FormatStyle getLLVMStyle() {
38 FormatStyle LLVMStyle;
39 LLVMStyle.ColumnLimit = 80;
40 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000041 LLVMStyle.PointerBindsToType = false;
42 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000043 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000044 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000045 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000046 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +000047 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000048 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000049 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000050 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000051 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000052 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +000053 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Daniel Jasperf7935112012-12-03 18:12:45 +000054 return LLVMStyle;
55}
56
57FormatStyle getGoogleStyle() {
58 FormatStyle GoogleStyle;
59 GoogleStyle.ColumnLimit = 80;
60 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000061 GoogleStyle.PointerBindsToType = true;
62 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000063 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000064 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000065 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000066 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000067 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000068 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000069 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +000070 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +000071 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000072 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +000073 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasperf7935112012-12-03 18:12:45 +000074 return GoogleStyle;
75}
76
Daniel Jasper1b750ed2013-01-14 16:24:39 +000077FormatStyle getChromiumStyle() {
78 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000079 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000080 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000081 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
82 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000083 return ChromiumStyle;
84}
85
Daniel Jasperacc33662013-02-08 08:22:00 +000086// Returns the length of everything up to the first possible line break after
87// the ), ], } or > matching \c Tok.
88static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
89 if (Tok.MatchingParen == NULL)
90 return 0;
91 AnnotatedToken *End = Tok.MatchingParen;
92 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
93 End = &End->Children[0];
94 }
95 return End->TotalLength - Tok.TotalLength + 1;
96}
97
Daniel Jasperf7935112012-12-03 18:12:45 +000098class UnwrappedLineFormatter {
99public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000100 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000101 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000102 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000103 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000104 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000105 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000106 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000107
Manuel Klimek1abf7892013-01-04 23:34:14 +0000108 /// \brief Formats an \c UnwrappedLine.
109 ///
110 /// \returns The column after the last token in the last line of the
111 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000112 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000113 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000114 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000115 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000116 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000117 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000118 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper97b89482013-03-13 07:49:51 +0000119 /*HasMultiParameterLine=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000120 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000121 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000122 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000123 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000124
125 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000126 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000127
Daniel Jasper4b866272013-02-01 11:00:45 +0000128 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000129 unsigned ColumnLimit = Style.ColumnLimit;
130 if (NextLine && NextLine->InPPDirective &&
131 !NextLine->First.FormatTok.HasUnescapedNewline)
132 ColumnLimit = getColumnLimit();
133 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000134 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000135 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000136 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000137 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000138 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000139
Daniel Jasperacc33662013-02-08 08:22:00 +0000140 // If the ObjC method declaration does not fit on a line, we should format
141 // it with one arg per line.
142 if (Line.Type == LT_ObjCMethodDecl)
143 State.Stack.back().BreakBeforeParameter = true;
144
Daniel Jasper4b866272013-02-01 11:00:45 +0000145 // Find best solution in solution space.
146 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000147 }
148
149private:
Manuel Klimek24998102013-01-16 14:55:28 +0000150 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
151 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000152 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
153 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000154 llvm::errs();
155 }
156
Daniel Jasper337816e2013-01-11 10:22:12 +0000157 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000158 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
159 bool HasMultiParameterLine)
Daniel Jasper400adc62013-02-08 15:28:42 +0000160 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
161 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000162 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000163 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasperc238c872013-04-02 14:33:13 +0000164 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
Daniel Jaspera628c982013-04-03 13:36:17 +0000165 CallContinuation(0), VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000166
Daniel Jasperf7935112012-12-03 18:12:45 +0000167 /// \brief The position to which a specific parenthesis level needs to be
168 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000169 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000170
Daniel Jaspere9de2602012-12-06 09:56:08 +0000171 /// \brief The position of the last space on each level.
172 ///
173 /// Used e.g. to break like:
174 /// functionCall(Parameter, otherCall(
175 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000176 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000177
Daniel Jaspere9de2602012-12-06 09:56:08 +0000178 /// \brief The position the first "<<" operator encountered on each level.
179 ///
180 /// Used to align "<<" operators. 0 if no such operator has been encountered
181 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000182 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000183
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000184 /// \brief Whether a newline needs to be inserted before the block's closing
185 /// brace.
186 ///
187 /// We only want to insert a newline before the closing brace if there also
188 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000189 bool BreakBeforeClosingBrace;
190
Daniel Jasperca6623b2013-01-28 12:45:14 +0000191 /// \brief The column of a \c ? in a conditional expression;
192 unsigned QuestionColumn;
193
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000194 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
195 /// lines, in this context.
196 bool AvoidBinPacking;
197
198 /// \brief Break after the next comma (or all the commas in this context if
199 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000200 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000201
202 /// \brief This context already has a line with more than one parameter.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000203 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000204
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000205 /// \brief The position of the colon in an ObjC method declaration/call.
206 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000207
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000208 /// \brief The start of the most recent function in a builder-type call.
209 unsigned StartOfFunctionCall;
210
Daniel Jasperc238c872013-04-02 14:33:13 +0000211 /// \brief If a nested name specifier was broken over multiple lines, this
212 /// contains the start column of the second line. Otherwise 0.
213 unsigned NestedNameSpecifierContinuation;
214
215 /// \brief If a call expression was broken over multiple lines, this
216 /// contains the start column of the second line. Otherwise 0.
217 unsigned CallContinuation;
218
Daniel Jaspera628c982013-04-03 13:36:17 +0000219 /// \brief The column of the first variable name in a variable declaration.
220 ///
221 /// Used to align further variables if necessary.
222 unsigned VariablePos;
223
Daniel Jasper337816e2013-01-11 10:22:12 +0000224 bool operator<(const ParenState &Other) const {
225 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000226 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000227 if (LastSpace != Other.LastSpace)
228 return LastSpace < Other.LastSpace;
229 if (FirstLessLess != Other.FirstLessLess)
230 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000231 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
232 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000233 if (QuestionColumn != Other.QuestionColumn)
234 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000235 if (AvoidBinPacking != Other.AvoidBinPacking)
236 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000237 if (BreakBeforeParameter != Other.BreakBeforeParameter)
238 return BreakBeforeParameter;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000239 if (HasMultiParameterLine != Other.HasMultiParameterLine)
240 return HasMultiParameterLine;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000241 if (ColonPos != Other.ColonPos)
242 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000243 if (StartOfFunctionCall != Other.StartOfFunctionCall)
244 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000245 if (NestedNameSpecifierContinuation !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000246 Other.NestedNameSpecifierContinuation)
Daniel Jasperc238c872013-04-02 14:33:13 +0000247 return NestedNameSpecifierContinuation <
248 Other.NestedNameSpecifierContinuation;
249 if (CallContinuation != Other.CallContinuation)
250 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000251 if (VariablePos != Other.VariablePos)
252 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000253 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000254 }
255 };
256
257 /// \brief The current state when indenting a unwrapped line.
258 ///
259 /// As the indenting tries different combinations this is copied by value.
260 struct LineState {
261 /// \brief The number of used columns in the current line.
262 unsigned Column;
263
264 /// \brief The token that needs to be next formatted.
265 const AnnotatedToken *NextToken;
266
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000267 /// \brief \c true if this line contains a continued for-loop section.
268 bool LineContainsContinuedForLoopSection;
269
Daniel Jasper400adc62013-02-08 15:28:42 +0000270 /// \brief The level of nesting inside (), [], <> and {}.
271 unsigned ParenLevel;
272
Daniel Jasper40c36c52013-02-18 11:05:07 +0000273 /// \brief The \c ParenLevel at the start of this line.
274 unsigned StartOfLineLevel;
275
Manuel Klimek02f640a2013-02-20 15:25:48 +0000276 /// \brief The start column of the string literal, if we're in a string
277 /// literal sequence, 0 otherwise.
278 unsigned StartOfStringLiteral;
279
Daniel Jasper337816e2013-01-11 10:22:12 +0000280 /// \brief A stack keeping track of properties applying to parenthesis
281 /// levels.
282 std::vector<ParenState> Stack;
283
284 /// \brief Comparison operator to be able to used \c LineState in \c map.
285 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000286 if (NextToken != Other.NextToken)
287 return NextToken < Other.NextToken;
288 if (Column != Other.Column)
289 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000290 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000291 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000292 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000293 if (ParenLevel != Other.ParenLevel)
294 return ParenLevel < Other.ParenLevel;
295 if (StartOfLineLevel != Other.StartOfLineLevel)
296 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000297 if (StartOfStringLiteral != Other.StartOfStringLiteral)
298 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000299 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000300 }
301 };
302
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000303 /// \brief Appends the next token to \p State and updates information
304 /// necessary for indentation.
305 ///
306 /// Puts the token on the current line if \p Newline is \c true and adds a
307 /// line break and necessary indentation otherwise.
308 ///
309 /// If \p DryRun is \c false, also creates and stores the required
310 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000311 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000312 const AnnotatedToken &Current = *State.NextToken;
313 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000314
Daniel Jasper291f9362013-03-20 15:58:10 +0000315 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000316 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
317 State.NextToken->FormatTok.TokenLength;
318 if (State.NextToken->Children.empty())
319 State.NextToken = NULL;
320 else
321 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000322 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000323 }
324
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000325 // If we are continuing an expression, we want to indent an extra 4 spaces.
326 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000327 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000329 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000330 if (Current.is(tok::r_brace)) {
331 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000332 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000333 State.StartOfStringLiteral != 0) {
334 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000335 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000336 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000337 State.Stack.back().FirstLessLess != 0) {
338 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000339 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000340 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
341 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000342 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000343 } else {
344 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
345 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000346 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000347 if (State.Stack.back().CallContinuation == 0) {
348 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000349 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000350 } else {
351 State.Column = State.Stack.back().CallContinuation;
352 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000353 } else if (Current.Type == TT_ConditionalExpr) {
354 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000355 } else if (Previous.is(tok::comma) &&
356 State.Stack.back().VariablePos != 0) {
357 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000358 } else if (Previous.ClosesTemplateDeclaration ||
359 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000360 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000361 } else if (Current.Type == TT_ObjCSelectorName) {
362 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
363 State.Column =
364 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
365 } else {
366 State.Column = State.Stack.back().Indent;
367 State.Stack.back().ColonPos =
368 State.Column + Current.FormatTok.TokenLength;
369 }
Daniel Jasper6bee6822013-04-08 20:33:42 +0000370 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000371 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000372 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000373 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000374 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000375 // Ensure that we fall back to indenting 4 spaces instead of just
376 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000377 if (State.Column == FirstIndent)
378 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000379 }
380
Daniel Jasper54a86022013-02-15 11:07:25 +0000381 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000382 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000383 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000384 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000385 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000386
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000387 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000388 unsigned NewLines = 1;
389 if (Current.Type == TT_LineComment)
390 NewLines =
391 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
392 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000393 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000394 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000395 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000396 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000397 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000398 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000399 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000400
Daniel Jasper400adc62013-02-08 15:28:42 +0000401 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000402 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000403
404 // Any break on this level means that the parent level has been broken
405 // and we need to avoid bin packing there.
406 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
407 State.Stack[i].BreakBeforeParameter = true;
408 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000409 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
410 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
411 !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000412 State.Stack.back().BreakBeforeParameter = true;
413
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000414 // If we break after {, we should also break before the corresponding }.
415 if (Previous.is(tok::l_brace))
416 State.Stack.back().BreakBeforeClosingBrace = true;
417
418 if (State.Stack.back().AvoidBinPacking) {
419 // If we are breaking after '(', '{', '<', this is not bin packing
420 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000421 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000422 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
423 Line.MustBeDeclaration))
424 State.Stack.back().BreakBeforeParameter = true;
425 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000427 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000428 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
429 State.Stack.back().VariablePos == 0) {
430 State.Stack.back().VariablePos = State.Column;
431 // Move over * and & if they are bound to the variable name.
432 const AnnotatedToken *Tok = &Previous;
433 while (Tok &&
434 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
435 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
436 if (Tok->SpacesRequiredBefore != 0)
437 break;
438 Tok = Tok->Parent;
439 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000440 if (Previous.PartOfMultiVariableDeclStmt)
441 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
442 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000443
Daniel Jaspereef30492013-02-11 12:36:37 +0000444 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000445
Daniel Jasperf7935112012-12-03 18:12:45 +0000446 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000447 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000448
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000449 if (Current.Type == TT_ObjCSelectorName &&
450 State.Stack.back().ColonPos == 0) {
451 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000452 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000453 State.Stack.back().ColonPos =
454 State.Stack.back().Indent + Current.LongestObjCSelectorName;
455 else
456 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000457 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000458 }
459
Daniel Jasperc04baae2013-04-10 09:49:49 +0000460 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000461 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000462 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000463 if (Previous.is(tok::comma) && !Current.isTrailingComment())
Daniel Jasper400adc62013-02-08 15:28:42 +0000464 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000465
Daniel Jaspere9de2602012-12-06 09:56:08 +0000466 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000467 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000468 // Treat the condition inside an if as if it was a second function
469 // parameter, i.e. let nested calls have an indent of 4.
470 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000471 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000472 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000473 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000474 Previous.Type == TT_ConditionalExpr ||
475 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000476 getPrecedence(Previous) != prec::Assignment)
477 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000478 else if (Previous.Type == TT_InheritanceColon)
479 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000480 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000481 // If this function has multiple parameters, indent nested calls from
482 // the start of the first parameter.
483 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000484 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000485
Manuel Klimek1998ea22013-02-20 10:15:13 +0000486 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000487 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000488
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000489 /// \brief Mark the next token as consumed in \p State and modify its stacks
490 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000491 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000492 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000493 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000494
Daniel Jaspereead02b2013-02-14 08:42:54 +0000495 if (Current.Type == TT_InheritanceColon)
496 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000497 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
498 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000499 if (Current.is(tok::question))
500 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000501 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000502 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
503 State.Stack.back().StartOfFunctionCall =
504 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000505 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000506 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000507 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
508 State.Stack.back().AvoidBinPacking = true;
509 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000510 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000511
Daniel Jasper6bee6822013-04-08 20:33:42 +0000512 // If return returns a binary expression, align after it.
513 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
514 State.Stack.back().LastSpace = State.Column + 7;
515
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000516 // In ObjC method declaration we align on the ":" of parameters, but we need
517 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000518 if (Current.Type == TT_ObjCMethodSpecifier)
519 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000520
Daniel Jasper400adc62013-02-08 15:28:42 +0000521 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000522 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
523 // Don't add extra indentation for the first fake parenthesis after
524 // 'return', assignements or opening <({[. The indentation for these cases
525 // is special cased.
526 bool SkipFirstExtraIndent =
527 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000528 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000529 getPrecedence(*Previous) == prec::Assignment));
530 for (SmallVector<prec::Level, 4>::const_reverse_iterator
531 I = Current.FakeLParens.rbegin(),
532 E = Current.FakeLParens.rend();
533 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000534 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000535 NewParenState.Indent =
536 std::max(std::max(State.Column, NewParenState.Indent),
537 State.Stack.back().LastSpace);
538
539 // Always indent conditional expressions. Never indent expression where
540 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
541 // prec::Assignment) as those have different indentation rules. Indent
542 // other expression, unless the indentation needs to be skipped.
543 if (*I == prec::Conditional ||
544 (!SkipFirstExtraIndent && *I > prec::Assignment))
545 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000546 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000547 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000548 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000549 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000550 }
551
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000552 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000553 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000554 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000555 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000556 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000557 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000558 NewIndent = 2 + State.Stack.back().LastSpace;
559 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000560 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000561 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
562 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000563 AvoidBinPacking =
564 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000565 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000566 State.Stack.push_back(
567 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
568 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000569 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000570 }
571
Daniel Jasperacc33662013-02-08 08:22:00 +0000572 // If this '[' opens an ObjC call, determine whether all parameters fit into
573 // one line and put one per line if they don't.
574 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
575 Current.MatchingParen != NULL) {
576 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
577 State.Stack.back().BreakBeforeParameter = true;
578 }
579
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000580 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000581 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000582 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000583 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
584 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000586 --State.ParenLevel;
587 }
588
589 // Remove scopes created by fake parenthesis.
590 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000591 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000592 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000593 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000594 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000595
Manuel Klimek0c915712013-02-20 15:32:58 +0000596 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000597 State.StartOfStringLiteral = State.Column;
598 } else if (Current.isNot(tok::comment)) {
599 State.StartOfStringLiteral = 0;
600 }
601
Manuel Klimek1998ea22013-02-20 10:15:13 +0000602 State.Column += Current.FormatTok.TokenLength;
603
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000604 if (State.NextToken->Children.empty())
605 State.NextToken = NULL;
606 else
607 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000608
Manuel Klimek1998ea22013-02-20 10:15:13 +0000609 return breakProtrudingToken(Current, State, DryRun);
610 }
611
612 /// \brief If the current token sticks out over the end of the line, break
613 /// it if possible.
614 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
615 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000616 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000617 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000618 if (Current.is(tok::string_literal)) {
619 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000620 const char *LiteralData = SourceMgr.getCharacterData(
621 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000622 if (!LiteralData || *LiteralData != '"')
623 return 0;
624
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000625 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
626 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000627 } else if (Current.Type == TT_BlockComment) {
628 BreakableBlockComment *BBC =
629 new BreakableBlockComment(SourceMgr, Current, StartColumn);
630 if (!DryRun)
631 BBC->alignLines(Whitespaces);
632 Token.reset(BBC);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000633 } else if (Current.Type == TT_LineComment) {
634 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000635 } else {
636 return 0;
637 }
638
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000639 bool BreakInserted = false;
640 unsigned Penalty = 0;
641 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
642 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000643 unsigned TailOffset = 0;
644 unsigned RemainingLength =
645 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
646 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000647 BreakableToken::Split Split =
648 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
649 if (Split.first == StringRef::npos)
650 break;
651 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000652 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
653 LineIndex, TailOffset + Split.first + Split.second);
654 if (NewRemainingLength >= RemainingLength)
655 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000656 if (!DryRun) {
657 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
658 Whitespaces);
659 }
660 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000661 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000662 Penalty += Style.PenaltyExcessCharacter;
663 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000664 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000665 State.Column = RemainingLength;
666 if (!DryRun) {
667 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
668 }
669 }
670
671 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000672 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
673 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000674 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000675 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000676 return Penalty;
677 }
678
Daniel Jasper2df93312013-01-09 10:16:05 +0000679 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000680 // In preprocessor directives reserve two chars for trailing " \"
681 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000682 }
683
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000684 /// \brief An edge in the solution space from \c Previous->State to \c State,
685 /// inserting a newline dependent on the \c NewLine.
686 struct StateNode {
687 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000688 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000689 LineState State;
690 bool NewLine;
691 StateNode *Previous;
692 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000693
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000694 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
695 ///
696 /// In case of equal penalties, we want to prefer states that were inserted
697 /// first. During state generation we make sure that we insert states first
698 /// that break the line as late as possible.
699 typedef std::pair<unsigned, unsigned> OrderedPenalty;
700
701 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
702 /// \c State has the given \c OrderedPenalty.
703 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
704
705 /// \brief The BFS queue type.
706 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
707 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000708
709 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000711 /// This implements a variant of Dijkstra's algorithm on the graph that spans
712 /// the solution space (\c LineStates are the nodes). The algorithm tries to
713 /// find the shortest path (the one with lowest penalty) from \p InitialState
714 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000715 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000716 std::set<LineState> Seen;
717
Daniel Jasper4b866272013-02-01 11:00:45 +0000718 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000719 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000720 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
721 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
722 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000723
724 // While not empty, take first element and follow edges.
725 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000726 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000727 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000728 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000729 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000730 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000731 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000732 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000733
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000734 if (!Seen.insert(Node->State).second)
735 // State already examined with lower penalty.
736 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000737
Manuel Klimekaf491072013-02-13 10:54:19 +0000738 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
739 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000740 }
741
742 if (Queue.empty())
743 // We were unable to find a solution, do nothing.
744 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 return 0;
746
Daniel Jasper4b866272013-02-01 11:00:45 +0000747 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000748 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000749 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000750
Daniel Jasper4b866272013-02-01 11:00:45 +0000751 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000752 return Queue.top().second->State.Column;
753 }
754
755 void reconstructPath(LineState &State, StateNode *Current) {
756 // FIXME: This recursive implementation limits the possible number
757 // of tokens per line if compiled into a binary with small stack space.
758 // To become more independent of stack frame limitations we would need
759 // to also change the TokenAnnotator.
760 if (Current->Previous == NULL)
761 return;
762 reconstructPath(State, Current->Previous);
763 DEBUG({
764 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000765 llvm::errs()
766 << "Penalty for splitting before "
767 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
768 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000769 }
770 });
771 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000772 }
773
Manuel Klimekaf491072013-02-13 10:54:19 +0000774 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000775 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000776 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000777 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000778 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
779 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000780 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000781 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000782 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000783 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000784 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000785 Penalty += PreviousNode->State.NextToken->SplitPenalty;
786
787 StateNode *Node = new (Allocator.Allocate())
788 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000789 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000790 if (Node->State.Column > getColumnLimit()) {
791 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000792 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000793 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000794
795 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
796 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000797 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000798
Daniel Jasper4b866272013-02-01 11:00:45 +0000799 /// \brief Returns \c true, if a line break after \p State is allowed.
800 bool canBreak(const LineState &State) {
801 if (!State.NextToken->CanBreakBefore &&
802 !(State.NextToken->is(tok::r_brace) &&
803 State.Stack.back().BreakBeforeClosingBrace))
804 return false;
805 // Trying to insert a parameter on a new line if there are already more than
806 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000807 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000808 State.Stack.back().AvoidBinPacking)
809 return false;
810 return true;
811 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000812
Daniel Jasper4b866272013-02-01 11:00:45 +0000813 /// \brief Returns \c true, if a line break after \p State is mandatory.
814 bool mustBreak(const LineState &State) {
815 if (State.NextToken->MustBreakBefore)
816 return true;
817 if (State.NextToken->is(tok::r_brace) &&
818 State.Stack.back().BreakBeforeClosingBrace)
819 return true;
820 if (State.NextToken->Parent->is(tok::semi) &&
821 State.LineContainsContinuedForLoopSection)
822 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000823 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000824 State.NextToken->is(tok::question) ||
825 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000826 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000827 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000828 State.NextToken->isNot(tok::r_paren) &&
829 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000830 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000831 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
832 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000833 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000834 State.NextToken->LongestObjCSelectorName == 0 &&
835 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000836 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000837 if ((State.NextToken->Type == TT_CtorInitializerColon ||
838 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000839 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000840 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000841 if (State.NextToken->Type == TT_InlineASMColon)
842 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000843 // This prevents breaks like:
844 // ...
845 // SomeParameter, OtherParameter).DoSomething(
846 // ...
847 // As they hide "DoSomething" and generally bad for readability.
848 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
849 getRemainingLength(State) + State.Column > getColumnLimit() &&
850 State.ParenLevel < State.StartOfLineLevel)
851 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000852 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000853 }
854
Daniel Jasper9b334242013-03-15 14:57:30 +0000855 // Returns the total number of columns required for the remaining tokens.
856 unsigned getRemainingLength(const LineState &State) {
857 if (State.NextToken && State.NextToken->Parent)
858 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
859 return 0;
860 }
861
Daniel Jasperf7935112012-12-03 18:12:45 +0000862 FormatStyle Style;
863 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000864 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000865 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000866 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000867 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000868
869 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
870 QueueType Queue;
871 // Increasing count of \c StateNode items we have created. This is used
872 // to create a deterministic order independent of the container.
873 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000874};
875
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000876class LexerBasedFormatTokenSource : public FormatTokenSource {
877public:
878 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000879 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000880 IdentTable(Lex.getLangOpts()) {
881 Lex.SetKeepWhitespaceMode(true);
882 }
883
884 virtual FormatToken getNextToken() {
885 if (GreaterStashed) {
886 FormatTok.NewlinesBefore = 0;
887 FormatTok.WhiteSpaceStart =
888 FormatTok.Tok.getLocation().getLocWithOffset(1);
889 FormatTok.WhiteSpaceLength = 0;
890 GreaterStashed = false;
891 return FormatTok;
892 }
893
894 FormatTok = FormatToken();
895 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000896 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000897 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000898 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
899 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000900
901 // Consume and record whitespace until we find a significant token.
902 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000903 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +0000904 if (Newlines > 0)
905 FormatTok.LastNewlineOffset =
906 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +0000907 unsigned EscapedNewlines = Text.count("\\\n");
908 FormatTok.NewlinesBefore += Newlines;
909 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000910 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
911
912 if (FormatTok.Tok.is(tok::eof))
913 return FormatTok;
914 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000915 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000916 }
Manuel Klimekef920692013-01-07 07:56:50 +0000917
918 // Now FormatTok is the next non-whitespace token.
919 FormatTok.TokenLength = Text.size();
920
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000921 if (FormatTok.Tok.is(tok::comment)) {
922 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
923 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
924 }
925
Manuel Klimek1abf7892013-01-04 23:34:14 +0000926 // In case the token starts with escaped newlines, we want to
927 // take them into account as whitespace - this pattern is quite frequent
928 // in macro definitions.
929 // FIXME: What do we want to do with other escaped spaces, and escaped
930 // spaces or newlines in the middle of tokens?
931 // FIXME: Add a more explicit test.
932 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000933 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000934 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000935 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000936 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000937 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000938 }
939
940 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000941 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000942 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000943 FormatTok.Tok.setKind(Info.getTokenID());
944 }
945
946 if (FormatTok.Tok.is(tok::greatergreater)) {
947 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +0000948 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000949 GreaterStashed = true;
950 }
951
952 return FormatTok;
953 }
954
Nico Weber29f9dea2013-02-11 15:32:15 +0000955 IdentifierTable &getIdentTable() { return IdentTable; }
956
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000957private:
958 FormatToken FormatTok;
959 bool GreaterStashed;
960 Lexer &Lex;
961 SourceManager &SourceMgr;
962 IdentifierTable IdentTable;
963
964 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000965 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000966 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
967 Tok.getLength());
968 }
969};
970
Daniel Jasperf7935112012-12-03 18:12:45 +0000971class Formatter : public UnwrappedLineConsumer {
972public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000973 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
974 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000975 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000976 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000977 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000978
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000979 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000980
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000981 tooling::Replacements format() {
982 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
983 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000984 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000985 unsigned PreviousEndOfLineColumn = 0;
986 TokenAnnotator Annotator(Style, SourceMgr, Lex,
987 Tokens.getIdentTable().get("in"));
988 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
989 Annotator.annotate(AnnotatedLines[i]);
990 }
991 deriveLocalStyle();
992 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
993 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
994 }
Daniel Jasperb67cc422013-04-09 17:46:55 +0000995
996 // Adapt level to the next line if this is a comment.
997 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +0000998 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +0000999 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1000 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1001 AnnotatedLines[i].First.Children.empty())
1002 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1003 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001004 NextNoneCommentLine =
1005 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1006 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001007 }
1008
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001009 std::vector<int> IndentForLevel;
1010 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001011 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001012 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1013 E = AnnotatedLines.end();
1014 I != E; ++I) {
1015 const AnnotatedLine &TheLine = *I;
1016 const FormatToken &FirstTok = TheLine.First.FormatTok;
1017 int Offset = getIndentOffset(TheLine.First);
1018 while (IndentForLevel.size() <= TheLine.Level)
1019 IndentForLevel.push_back(-1);
1020 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001021 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001022 if (TheLine.First.is(tok::eof)) {
1023 if (PreviousLineWasTouched) {
1024 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1025 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001026 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001027 }
1028 } else if (TheLine.Type != LT_Invalid &&
1029 (WasMoved || touchesLine(TheLine))) {
1030 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1031 unsigned Indent = LevelIndent;
1032 if (static_cast<int>(Indent) + Offset >= 0)
1033 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001034 if (FirstTok.WhiteSpaceStart.isValid() &&
1035 // Insert a break even if there is a structural error in case where
1036 // we break apart a line consisting of multiple unwrapped lines.
1037 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001038 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1039 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001040 } else {
1041 Indent = LevelIndent =
1042 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001043 }
1044 tryFitMultipleLinesInOne(Indent, I, E);
1045 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001046 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001047 PreviousEndOfLineColumn =
1048 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1049 IndentForLevel[TheLine.Level] = LevelIndent;
1050 PreviousLineWasTouched = true;
1051 } else {
1052 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1053 unsigned Indent =
1054 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1055 unsigned LevelIndent = Indent;
1056 if (static_cast<int>(LevelIndent) - Offset >= 0)
1057 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001058 if (TheLine.First.isNot(tok::comment))
1059 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001060
1061 // Remove trailing whitespace of the previous line if it was touched.
1062 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001063 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1064 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001065 }
1066 // If we did not reformat this unwrapped line, the column at the end of
1067 // the last token is unchanged - thus, we can calculate the end of the
1068 // last token.
1069 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1070 PreviousEndOfLineColumn =
1071 SourceMgr.getSpellingColumnNumber(LastLoc) +
1072 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1073 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001074 if (TheLine.Last->is(tok::comment))
1075 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1076 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001077 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001078 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001079 }
1080 return Whitespaces.generateReplacements();
1081 }
1082
1083private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001084 void deriveLocalStyle() {
1085 unsigned CountBoundToVariable = 0;
1086 unsigned CountBoundToType = 0;
1087 bool HasCpp03IncompatibleFormat = false;
1088 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1089 if (AnnotatedLines[i].First.Children.empty())
1090 continue;
1091 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1092 while (!Tok->Children.empty()) {
1093 if (Tok->Type == TT_PointerOrReference) {
1094 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1095 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1096 if (SpacesBefore && !SpacesAfter)
1097 ++CountBoundToVariable;
1098 else if (!SpacesBefore && SpacesAfter)
1099 ++CountBoundToType;
1100 }
1101
Daniel Jasper400adc62013-02-08 15:28:42 +00001102 if (Tok->Type == TT_TemplateCloser &&
1103 Tok->Parent->Type == TT_TemplateCloser &&
1104 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001105 HasCpp03IncompatibleFormat = true;
1106 Tok = &Tok->Children[0];
1107 }
1108 }
1109 if (Style.DerivePointerBinding) {
1110 if (CountBoundToType > CountBoundToVariable)
1111 Style.PointerBindsToType = true;
1112 else if (CountBoundToType < CountBoundToVariable)
1113 Style.PointerBindsToType = false;
1114 }
1115 if (Style.Standard == FormatStyle::LS_Auto) {
1116 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1117 : FormatStyle::LS_Cpp03;
1118 }
1119 }
1120
Manuel Klimekb95f5452013-02-08 17:38:27 +00001121 /// \brief Get the indent of \p Level from \p IndentForLevel.
1122 ///
1123 /// \p IndentForLevel must contain the indent for the level \c l
1124 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1125 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001126 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001127 if (IndentForLevel[Level] != -1)
1128 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001129 if (Level == 0)
1130 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001131 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001132 }
1133
1134 /// \brief Get the offset of the line relatively to the level.
1135 ///
1136 /// For example, 'public:' labels in classes are offset by 1 or 2
1137 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001138 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001139 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001140 return Style.AccessModifierOffset;
1141 return 0;
1142 }
1143
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001144 /// \brief Tries to merge lines into one.
1145 ///
1146 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1147 /// if possible; note that \c I will be incremented when lines are merged.
1148 ///
1149 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001150 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001151 std::vector<AnnotatedLine>::iterator &I,
1152 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001153 // We can never merge stuff if there are trailing line comments.
1154 if (I->Last->Type == TT_LineComment)
1155 return;
1156
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001157 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001158 // If we already exceed the column limit, we set 'Limit' to 0. The different
1159 // tryMerge..() functions can then decide whether to still do merging.
1160 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001161
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001162 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001163 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001164
Daniel Jasper25837aa2013-01-14 14:14:23 +00001165 if (I->Last->is(tok::l_brace)) {
1166 tryMergeSimpleBlock(I, E, Limit);
1167 } else if (I->First.is(tok::kw_if)) {
1168 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001169 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1170 I->First.FormatTok.IsFirst)) {
1171 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001172 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001173 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001174 }
1175
Daniel Jasper39825ea2013-01-14 15:40:57 +00001176 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1177 std::vector<AnnotatedLine>::iterator E,
1178 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001179 if (Limit == 0)
1180 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001181 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001182 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1183 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001184 if (I + 2 != E && (I + 2)->InPPDirective &&
1185 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1186 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001187 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001188 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001189 join(Line, *(++I));
1190 }
1191
Daniel Jasper25837aa2013-01-14 14:14:23 +00001192 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1193 std::vector<AnnotatedLine>::iterator E,
1194 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001195 if (Limit == 0)
1196 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001197 if (!Style.AllowShortIfStatementsOnASingleLine)
1198 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001199 if ((I + 1)->InPPDirective != I->InPPDirective ||
1200 ((I + 1)->InPPDirective &&
1201 (I + 1)->First.FormatTok.HasUnescapedNewline))
1202 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001203 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001204 if (Line.Last->isNot(tok::r_paren))
1205 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001206 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001207 return;
1208 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1209 return;
1210 // Only inline simple if's (no nested if or else).
1211 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1212 return;
1213 join(Line, *(++I));
1214 }
1215
1216 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001217 std::vector<AnnotatedLine>::iterator E,
1218 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001219 // First, check that the current line allows merging. This is the case if
1220 // we're not in a control flow statement and the last token is an opening
1221 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001222 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001223 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1224 tok::kw_else, tok::kw_try, tok::kw_catch,
1225 tok::kw_for,
1226 // This gets rid of all ObjC @ keywords and methods.
1227 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001228 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001229
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001230 AnnotatedToken *Tok = &(I + 1)->First;
1231 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001232 !Tok->MustBreakBefore) {
1233 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001234 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001235 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001236 join(Line, *(I + 1));
1237 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001238 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001239 // Check that we still have three lines and they fit into the limit.
1240 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1241 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001242 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001243
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001244 // Second, check that the next line does not contain any braces - if it
1245 // does, readability declines when putting it into a single line.
1246 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1247 return;
1248 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001249 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001250 return;
1251 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1252 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001253
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001254 // Last, check that the third line contains a single closing brace.
1255 Tok = &(I + 2)->First;
1256 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1257 Tok->MustBreakBefore)
1258 return;
1259
1260 join(Line, *(I + 1));
1261 join(Line, *(I + 2));
1262 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001263 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001264 }
1265
1266 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1267 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001268 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1269 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001270 }
1271
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001272 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001273 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001274 A.Last->Children.push_back(B.First);
1275 while (!A.Last->Children.empty()) {
1276 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001277 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001278 A.Last = &A.Last->Children[0];
1279 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001280 }
1281
Daniel Jasper97b89482013-03-13 07:49:51 +00001282 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001283 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1284 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1285 Ranges[i].getBegin()) &&
1286 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1287 Range.getBegin()))
1288 return true;
1289 }
1290 return false;
1291 }
1292
1293 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001294 const FormatToken *First = &TheLine.First.FormatTok;
1295 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001296 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001297 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1298 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001299 return touchesRanges(LineRange);
1300 }
1301
1302 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1303 const FormatToken *First = &TheLine.First.FormatTok;
1304 CharSourceRange LineRange = CharSourceRange::getCharRange(
1305 First->WhiteSpaceStart,
1306 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1307 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001308 }
1309
1310 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001311 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001312 }
1313
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001314 /// \brief Add a new line and the required indent before the first Token
1315 /// of the \c UnwrappedLine if there was no structural parsing error.
1316 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001317 void formatFirstToken(const AnnotatedToken &RootToken,
1318 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001319 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001320 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001321
Daniel Jasperbbc84152013-01-29 11:27:30 +00001322 unsigned Newlines =
1323 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001324 if (Newlines == 0 && !Tok.IsFirst)
1325 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001326
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001327 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001328 // Insert extra new line before access specifiers.
1329 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1330 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1331 ++Newlines;
1332
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001333 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001334 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001335 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001336 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001337 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001338 }
1339
Alexander Kornienko116ba682013-01-14 11:34:14 +00001340 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001341 FormatStyle Style;
1342 Lexer &Lex;
1343 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001344 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001345 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001346 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001347};
1348
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001349tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1350 SourceManager &SourceMgr,
1351 std::vector<CharSourceRange> Ranges,
1352 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001353 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001354 OwningPtr<DiagnosticConsumer> DiagPrinter;
1355 if (DiagClient == 0) {
1356 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1357 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1358 DiagClient = DiagPrinter.get();
1359 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001360 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001361 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001362 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001363 Diagnostics.setSourceManager(&SourceMgr);
1364 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001365 return formatter.format();
1366}
1367
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001368LangOptions getFormattingLangOpts() {
1369 LangOptions LangOpts;
1370 LangOpts.CPlusPlus = 1;
1371 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001372 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001373 LangOpts.Bool = 1;
1374 LangOpts.ObjC1 = 1;
1375 LangOpts.ObjC2 = 1;
1376 return LangOpts;
1377}
1378
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001379} // namespace format
1380} // namespace clang