blob: 68626d29ca06d33bb51a24fffeadb86ce36eae47 [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 Jasper6fe2f002013-04-25 08:56:26 +000054 LLVMStyle.AlignEscapedNewlinesLeft = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000055 return LLVMStyle;
56}
57
58FormatStyle getGoogleStyle() {
59 FormatStyle GoogleStyle;
60 GoogleStyle.ColumnLimit = 80;
61 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000062 GoogleStyle.PointerBindsToType = true;
63 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000064 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000065 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000066 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +000067 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000068 GoogleStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +000069 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +000070 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasper085a2ed2013-04-24 13:46:00 +000071 GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
Nico Webera6087752013-01-10 20:12:55 +000072 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper3a9370c2013-02-04 07:21:18 +000073 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper6728fc12013-04-11 14:29:13 +000074 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasper6fe2f002013-04-25 08:56:26 +000075 GoogleStyle.AlignEscapedNewlinesLeft = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000076 return GoogleStyle;
77}
78
Daniel Jasper1b750ed2013-01-14 16:24:39 +000079FormatStyle getChromiumStyle() {
80 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +000081 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper085a2ed2013-04-24 13:46:00 +000082 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
Daniel Jasper2cf17bf2013-02-27 09:47:53 +000083 ChromiumStyle.BinPackParameters = false;
Daniel Jasper7fce3ab2013-02-06 14:22:40 +000084 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
85 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +000086 return ChromiumStyle;
87}
88
Daniel Jasperacc33662013-02-08 08:22:00 +000089// Returns the length of everything up to the first possible line break after
90// the ), ], } or > matching \c Tok.
91static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
92 if (Tok.MatchingParen == NULL)
93 return 0;
94 AnnotatedToken *End = Tok.MatchingParen;
95 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
96 End = &End->Children[0];
97 }
98 return End->TotalLength - Tok.TotalLength + 1;
99}
100
Daniel Jasperf7935112012-12-03 18:12:45 +0000101class UnwrappedLineFormatter {
102public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000103 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000104 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000105 const AnnotatedToken &RootToken,
Manuel Klimek1a18c402013-04-12 14:13:36 +0000106 WhitespaceManager &Whitespaces)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000107 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000108 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000109 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000110
Manuel Klimek1abf7892013-01-04 23:34:14 +0000111 /// \brief Formats an \c UnwrappedLine.
112 ///
113 /// \returns The column after the last token in the last line of the
114 /// \c UnwrappedLine.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000115 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000116 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000117 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000118 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000119 State.NextToken = &RootToken;
Daniel Jasper97b89482013-03-13 07:49:51 +0000120 State.Stack.push_back(
Daniel Jasperc238c872013-04-02 14:33:13 +0000121 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000122 /*NoLineBreak=*/ false));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000123 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000124 State.ParenLevel = 0;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000125 State.StartOfStringLiteral = 0;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000126 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000127
128 // The first token has already been indented and thus consumed.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000129 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000130
Daniel Jasper4b866272013-02-01 11:00:45 +0000131 // If everything fits on a single line, just put it there.
Daniel Jasperc22f5b42013-02-28 11:05:57 +0000132 unsigned ColumnLimit = Style.ColumnLimit;
133 if (NextLine && NextLine->InPPDirective &&
134 !NextLine->First.FormatTok.HasUnescapedNewline)
135 ColumnLimit = getColumnLimit();
136 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000137 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000138 addTokenToState(false, false, State);
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000139 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000140 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000141 }
Daniel Jasper4b866272013-02-01 11:00:45 +0000142
Daniel Jasperacc33662013-02-08 08:22:00 +0000143 // If the ObjC method declaration does not fit on a line, we should format
144 // it with one arg per line.
145 if (Line.Type == LT_ObjCMethodDecl)
146 State.Stack.back().BreakBeforeParameter = true;
147
Daniel Jasper4b866272013-02-01 11:00:45 +0000148 // Find best solution in solution space.
149 return analyzeSolutionSpace(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000150 }
151
152private:
Manuel Klimek24998102013-01-16 14:55:28 +0000153 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
154 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000155 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
156 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000157 llvm::errs();
158 }
159
Daniel Jasper337816e2013-01-11 10:22:12 +0000160 struct ParenState {
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000161 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000162 bool NoLineBreak)
Daniel Jasper400adc62013-02-08 15:28:42 +0000163 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
164 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperacc33662013-02-08 08:22:00 +0000165 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000166 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
167 NestedNameSpecifierContinuation(0), CallContinuation(0),
168 VariablePos(0) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000169
Daniel Jasperf7935112012-12-03 18:12:45 +0000170 /// \brief The position to which a specific parenthesis level needs to be
171 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000172 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000173
Daniel Jaspere9de2602012-12-06 09:56:08 +0000174 /// \brief The position of the last space on each level.
175 ///
176 /// Used e.g. to break like:
177 /// functionCall(Parameter, otherCall(
178 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000179 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000180
Daniel Jaspere9de2602012-12-06 09:56:08 +0000181 /// \brief The position the first "<<" operator encountered on each level.
182 ///
183 /// Used to align "<<" operators. 0 if no such operator has been encountered
184 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000185 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000186
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000187 /// \brief Whether a newline needs to be inserted before the block's closing
188 /// brace.
189 ///
190 /// We only want to insert a newline before the closing brace if there also
191 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000192 bool BreakBeforeClosingBrace;
193
Daniel Jasperca6623b2013-01-28 12:45:14 +0000194 /// \brief The column of a \c ? in a conditional expression;
195 unsigned QuestionColumn;
196
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000197 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
198 /// lines, in this context.
199 bool AvoidBinPacking;
200
201 /// \brief Break after the next comma (or all the commas in this context if
202 /// \c AvoidBinPacking is \c true).
Daniel Jasperacc33662013-02-08 08:22:00 +0000203 bool BreakBeforeParameter;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000204
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000205 /// \brief Line breaking in this context would break a formatting rule.
206 bool NoLineBreak;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000207
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000208 /// \brief The position of the colon in an ObjC method declaration/call.
209 unsigned ColonPos;
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000210
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000211 /// \brief The start of the most recent function in a builder-type call.
212 unsigned StartOfFunctionCall;
213
Daniel Jasperc238c872013-04-02 14:33:13 +0000214 /// \brief If a nested name specifier was broken over multiple lines, this
215 /// contains the start column of the second line. Otherwise 0.
216 unsigned NestedNameSpecifierContinuation;
217
218 /// \brief If a call expression was broken over multiple lines, this
219 /// contains the start column of the second line. Otherwise 0.
220 unsigned CallContinuation;
221
Daniel Jaspera628c982013-04-03 13:36:17 +0000222 /// \brief The column of the first variable name in a variable declaration.
223 ///
224 /// Used to align further variables if necessary.
225 unsigned VariablePos;
226
Daniel Jasper337816e2013-01-11 10:22:12 +0000227 bool operator<(const ParenState &Other) const {
228 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000229 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000230 if (LastSpace != Other.LastSpace)
231 return LastSpace < Other.LastSpace;
232 if (FirstLessLess != Other.FirstLessLess)
233 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000234 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
235 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000236 if (QuestionColumn != Other.QuestionColumn)
237 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000238 if (AvoidBinPacking != Other.AvoidBinPacking)
239 return AvoidBinPacking;
Daniel Jasperacc33662013-02-08 08:22:00 +0000240 if (BreakBeforeParameter != Other.BreakBeforeParameter)
241 return BreakBeforeParameter;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000242 if (NoLineBreak != Other.NoLineBreak)
243 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000244 if (ColonPos != Other.ColonPos)
245 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000246 if (StartOfFunctionCall != Other.StartOfFunctionCall)
247 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000248 if (NestedNameSpecifierContinuation !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000249 Other.NestedNameSpecifierContinuation)
Daniel Jasperc238c872013-04-02 14:33:13 +0000250 return NestedNameSpecifierContinuation <
251 Other.NestedNameSpecifierContinuation;
252 if (CallContinuation != Other.CallContinuation)
253 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000254 if (VariablePos != Other.VariablePos)
255 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000256 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000257 }
258 };
259
260 /// \brief The current state when indenting a unwrapped line.
261 ///
262 /// As the indenting tries different combinations this is copied by value.
263 struct LineState {
264 /// \brief The number of used columns in the current line.
265 unsigned Column;
266
267 /// \brief The token that needs to be next formatted.
268 const AnnotatedToken *NextToken;
269
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000270 /// \brief \c true if this line contains a continued for-loop section.
271 bool LineContainsContinuedForLoopSection;
272
Daniel Jasper400adc62013-02-08 15:28:42 +0000273 /// \brief The level of nesting inside (), [], <> and {}.
274 unsigned ParenLevel;
275
Daniel Jasper40c36c52013-02-18 11:05:07 +0000276 /// \brief The \c ParenLevel at the start of this line.
277 unsigned StartOfLineLevel;
278
Manuel Klimek02f640a2013-02-20 15:25:48 +0000279 /// \brief The start column of the string literal, if we're in a string
280 /// literal sequence, 0 otherwise.
281 unsigned StartOfStringLiteral;
282
Daniel Jasper337816e2013-01-11 10:22:12 +0000283 /// \brief A stack keeping track of properties applying to parenthesis
284 /// levels.
285 std::vector<ParenState> Stack;
286
287 /// \brief Comparison operator to be able to used \c LineState in \c map.
288 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000289 if (NextToken != Other.NextToken)
290 return NextToken < Other.NextToken;
291 if (Column != Other.Column)
292 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000293 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000294 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000295 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000296 if (ParenLevel != Other.ParenLevel)
297 return ParenLevel < Other.ParenLevel;
298 if (StartOfLineLevel != Other.StartOfLineLevel)
299 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000300 if (StartOfStringLiteral != Other.StartOfStringLiteral)
301 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000302 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000303 }
304 };
305
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000306 /// \brief Appends the next token to \p State and updates information
307 /// necessary for indentation.
308 ///
309 /// Puts the token on the current line if \p Newline is \c true and adds a
310 /// line break and necessary indentation otherwise.
311 ///
312 /// If \p DryRun is \c false, also creates and stores the required
313 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000314 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000315 const AnnotatedToken &Current = *State.NextToken;
316 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000317
Daniel Jasper291f9362013-03-20 15:58:10 +0000318 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000319 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
320 State.NextToken->FormatTok.TokenLength;
321 if (State.NextToken->Children.empty())
322 State.NextToken = NULL;
323 else
324 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000325 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000326 }
327
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000328 // If we are continuing an expression, we want to indent an extra 4 spaces.
329 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000330 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000331 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000332 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000333 if (Current.is(tok::r_brace)) {
334 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000335 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000336 State.StartOfStringLiteral != 0) {
337 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000338 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000339 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000340 State.Stack.back().FirstLessLess != 0) {
341 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000342 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000343 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
344 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000345 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000346 } else {
347 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
348 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000349 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000350 if (State.Stack.back().CallContinuation == 0) {
351 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000352 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000353 } else {
354 State.Column = State.Stack.back().CallContinuation;
355 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000356 } else if (Current.Type == TT_ConditionalExpr) {
357 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000358 } else if (Previous.is(tok::comma) &&
359 State.Stack.back().VariablePos != 0) {
360 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000361 } else if (Previous.ClosesTemplateDeclaration ||
Daniel Jasper8e357692013-05-06 08:27:33 +0000362 (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
363 Line.StartsDefinition)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000364 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000365 } else if (Current.Type == TT_ObjCSelectorName) {
366 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
367 State.Column =
368 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
369 } else {
370 State.Column = State.Stack.back().Indent;
371 State.Stack.back().ColonPos =
372 State.Column + Current.FormatTok.TokenLength;
373 }
Daniel Jasper6bee6822013-04-08 20:33:42 +0000374 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000375 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000376 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000377 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000378 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000379 // Ensure that we fall back to indenting 4 spaces instead of just
380 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000381 if (State.Column == FirstIndent)
382 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000383 }
384
Daniel Jasper54a86022013-02-15 11:07:25 +0000385 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000386 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000387 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000388 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000389 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000390
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000391 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000392 unsigned NewLines = 1;
393 if (Current.Type == TT_LineComment)
394 NewLines =
395 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
396 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000397 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000398 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000399 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000400 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000401 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000402 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000403 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000404
Daniel Jasper400adc62013-02-08 15:28:42 +0000405 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000406 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000407
408 // Any break on this level means that the parent level has been broken
409 // and we need to avoid bin packing there.
410 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
411 State.Stack[i].BreakBeforeParameter = true;
412 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000413 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
414 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
415 !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000416 State.Stack.back().BreakBeforeParameter = true;
417
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000418 // If we break after {, we should also break before the corresponding }.
419 if (Previous.is(tok::l_brace))
420 State.Stack.back().BreakBeforeClosingBrace = true;
421
422 if (State.Stack.back().AvoidBinPacking) {
423 // If we are breaking after '(', '{', '<', this is not bin packing
424 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000425 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000426 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
427 Line.MustBeDeclaration))
428 State.Stack.back().BreakBeforeParameter = true;
429 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000430 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000431 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000432 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
433 State.Stack.back().VariablePos == 0) {
434 State.Stack.back().VariablePos = State.Column;
435 // Move over * and & if they are bound to the variable name.
436 const AnnotatedToken *Tok = &Previous;
437 while (Tok &&
438 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
439 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
440 if (Tok->SpacesRequiredBefore != 0)
441 break;
442 Tok = Tok->Parent;
443 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000444 if (Previous.PartOfMultiVariableDeclStmt)
445 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
446 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000447
Daniel Jaspereef30492013-02-11 12:36:37 +0000448 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000449
Daniel Jasperf7935112012-12-03 18:12:45 +0000450 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000451 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000452
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000453 if (Current.Type == TT_ObjCSelectorName &&
454 State.Stack.back().ColonPos == 0) {
455 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000456 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000457 State.Stack.back().ColonPos =
458 State.Stack.back().Indent + Current.LongestObjCSelectorName;
459 else
460 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000461 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000462 }
463
Daniel Jasperc04baae2013-04-10 09:49:49 +0000464 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000465 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000466 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000467 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
468 State.Stack.back().AvoidBinPacking)
469 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000470
Daniel Jaspere9de2602012-12-06 09:56:08 +0000471 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000472 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000473 // Treat the condition inside an if as if it was a second function
474 // parameter, i.e. let nested calls have an indent of 4.
475 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000476 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000477 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000478 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000479 Previous.Type == TT_ConditionalExpr ||
480 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000481 getPrecedence(Previous) != prec::Assignment)
482 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000483 else if (Previous.Type == TT_InheritanceColon)
484 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000485 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000486 // If this function has multiple parameters, indent nested calls from
487 // the start of the first parameter.
488 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000489 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000490
Manuel Klimek1998ea22013-02-20 10:15:13 +0000491 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000492 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000493
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000494 /// \brief Mark the next token as consumed in \p State and modify its stacks
495 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000496 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000497 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000498 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000499
Daniel Jaspereead02b2013-02-14 08:42:54 +0000500 if (Current.Type == TT_InheritanceColon)
501 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000502 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
503 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000504 if (Current.is(tok::question))
505 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000506 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000507 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
508 State.Stack.back().StartOfFunctionCall =
509 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000510 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000511 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000512 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
513 State.Stack.back().AvoidBinPacking = true;
514 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000515 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000516
Daniel Jasper6bee6822013-04-08 20:33:42 +0000517 // If return returns a binary expression, align after it.
518 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
519 State.Stack.back().LastSpace = State.Column + 7;
520
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000521 // In ObjC method declaration we align on the ":" of parameters, but we need
522 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000523 if (Current.Type == TT_ObjCMethodSpecifier)
524 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000525
Daniel Jasper400adc62013-02-08 15:28:42 +0000526 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000527 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
528 // Don't add extra indentation for the first fake parenthesis after
529 // 'return', assignements or opening <({[. The indentation for these cases
530 // is special cased.
531 bool SkipFirstExtraIndent =
532 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000533 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000534 getPrecedence(*Previous) == prec::Assignment));
535 for (SmallVector<prec::Level, 4>::const_reverse_iterator
536 I = Current.FakeLParens.rbegin(),
537 E = Current.FakeLParens.rend();
538 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000539 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000540 NewParenState.Indent =
541 std::max(std::max(State.Column, NewParenState.Indent),
542 State.Stack.back().LastSpace);
543
544 // Always indent conditional expressions. Never indent expression where
545 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
546 // prec::Assignment) as those have different indentation rules. Indent
547 // other expression, unless the indentation needs to be skipped.
548 if (*I == prec::Conditional ||
549 (!SkipFirstExtraIndent && *I > prec::Assignment))
550 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000551 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000552 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000553 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000554 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000555 }
556
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000557 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000558 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000559 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000560 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000561 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000562 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000563 NewIndent = 2 + State.Stack.back().LastSpace;
564 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000565 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000566 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
567 State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000568 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000569 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000570 State.Stack.push_back(
571 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000572 State.Stack.back().NoLineBreak));
Daniel Jaspere3c0e012013-04-25 13:31:51 +0000573
574 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
575 // This parenthesis was the last token possibly making use of Indent and
576 // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
577 // better memoization results.
578 State.Stack[State.Stack.size() - 2].Indent = 0;
579 State.Stack[State.Stack.size() - 2].LastSpace = 0;
580 }
581
Daniel Jasper400adc62013-02-08 15:28:42 +0000582 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000583 }
584
Daniel Jasperacc33662013-02-08 08:22:00 +0000585 // If this '[' opens an ObjC call, determine whether all parameters fit into
586 // one line and put one per line if they don't.
587 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
588 Current.MatchingParen != NULL) {
589 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
590 State.Stack.back().BreakBeforeParameter = true;
591 }
592
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000593 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000594 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000595 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000596 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
597 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000598 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000599 --State.ParenLevel;
600 }
601
602 // Remove scopes created by fake parenthesis.
603 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000604 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000605 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000606 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000608
Manuel Klimek0c915712013-02-20 15:32:58 +0000609 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000610 State.StartOfStringLiteral = State.Column;
611 } else if (Current.isNot(tok::comment)) {
612 State.StartOfStringLiteral = 0;
613 }
614
Manuel Klimek1998ea22013-02-20 10:15:13 +0000615 State.Column += Current.FormatTok.TokenLength;
616
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000617 if (State.NextToken->Children.empty())
618 State.NextToken = NULL;
619 else
620 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000621
Manuel Klimek1998ea22013-02-20 10:15:13 +0000622 return breakProtrudingToken(Current, State, DryRun);
623 }
624
625 /// \brief If the current token sticks out over the end of the line, break
626 /// it if possible.
627 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
628 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000629 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000630 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000631 if (Current.is(tok::string_literal)) {
632 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000633 const char *LiteralData = SourceMgr.getCharacterData(
634 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000635 if (!LiteralData || *LiteralData != '"')
636 return 0;
637
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000638 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
639 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000640 } else if (Current.Type == TT_BlockComment) {
641 BreakableBlockComment *BBC =
642 new BreakableBlockComment(SourceMgr, Current, StartColumn);
643 if (!DryRun)
644 BBC->alignLines(Whitespaces);
645 Token.reset(BBC);
Daniel Jasper4a4be012013-05-06 10:24:51 +0000646 } else if (Current.Type == TT_LineComment &&
647 (Current.Parent == NULL ||
648 Current.Parent->Type != TT_ImplicitStringLiteral)) {
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000649 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000650 } else {
651 return 0;
652 }
653
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000654 bool BreakInserted = false;
655 unsigned Penalty = 0;
656 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
657 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000658 unsigned TailOffset = 0;
659 unsigned RemainingLength =
660 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
661 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000662 BreakableToken::Split Split =
663 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
664 if (Split.first == StringRef::npos)
665 break;
666 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000667 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
668 LineIndex, TailOffset + Split.first + Split.second);
669 if (NewRemainingLength >= RemainingLength)
670 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000671 if (!DryRun) {
672 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
673 Whitespaces);
674 }
675 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000676 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000677 Penalty += Style.PenaltyExcessCharacter;
678 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000679 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000680 State.Column = RemainingLength;
681 if (!DryRun) {
682 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
683 }
684 }
685
686 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000687 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
688 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000689 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000690 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000691 return Penalty;
692 }
693
Daniel Jasper2df93312013-01-09 10:16:05 +0000694 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000695 // In preprocessor directives reserve two chars for trailing " \"
696 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000697 }
698
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000699 /// \brief An edge in the solution space from \c Previous->State to \c State,
700 /// inserting a newline dependent on the \c NewLine.
701 struct StateNode {
702 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000703 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000704 LineState State;
705 bool NewLine;
706 StateNode *Previous;
707 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000708
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000709 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
710 ///
711 /// In case of equal penalties, we want to prefer states that were inserted
712 /// first. During state generation we make sure that we insert states first
713 /// that break the line as late as possible.
714 typedef std::pair<unsigned, unsigned> OrderedPenalty;
715
716 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
717 /// \c State has the given \c OrderedPenalty.
718 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
719
720 /// \brief The BFS queue type.
721 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
722 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000723
724 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000725 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000726 /// This implements a variant of Dijkstra's algorithm on the graph that spans
727 /// the solution space (\c LineStates are the nodes). The algorithm tries to
728 /// find the shortest path (the one with lowest penalty) from \p InitialState
729 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000730 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000731 std::set<LineState> Seen;
732
Daniel Jasper4b866272013-02-01 11:00:45 +0000733 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000734 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000735 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
736 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
737 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000738
739 // While not empty, take first element and follow edges.
740 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000741 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000742 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000743 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000744 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000745 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000746 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000747 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000748
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000749 if (!Seen.insert(Node->State).second)
750 // State already examined with lower penalty.
751 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000752
Manuel Klimekaf491072013-02-13 10:54:19 +0000753 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
754 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000755 }
756
757 if (Queue.empty())
758 // We were unable to find a solution, do nothing.
759 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000760 return 0;
761
Daniel Jasper4b866272013-02-01 11:00:45 +0000762 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000763 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000764 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000765
Daniel Jasper4b866272013-02-01 11:00:45 +0000766 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000767 return Queue.top().second->State.Column;
768 }
769
770 void reconstructPath(LineState &State, StateNode *Current) {
771 // FIXME: This recursive implementation limits the possible number
772 // of tokens per line if compiled into a binary with small stack space.
773 // To become more independent of stack frame limitations we would need
774 // to also change the TokenAnnotator.
775 if (Current->Previous == NULL)
776 return;
777 reconstructPath(State, Current->Previous);
778 DEBUG({
779 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000780 llvm::errs()
781 << "Penalty for splitting before "
782 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
783 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000784 }
785 });
786 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000787 }
788
Manuel Klimekaf491072013-02-13 10:54:19 +0000789 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000790 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000791 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000792 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000793 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
794 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000795 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000796 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000797 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000798 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000799 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000800 Penalty += PreviousNode->State.NextToken->SplitPenalty;
801
802 StateNode *Node = new (Allocator.Allocate())
803 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000804 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000805 if (Node->State.Column > getColumnLimit()) {
806 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000807 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000808 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000809
810 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
811 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000812 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000813
Daniel Jasper4b866272013-02-01 11:00:45 +0000814 /// \brief Returns \c true, if a line break after \p State is allowed.
815 bool canBreak(const LineState &State) {
816 if (!State.NextToken->CanBreakBefore &&
817 !(State.NextToken->is(tok::r_brace) &&
818 State.Stack.back().BreakBeforeClosingBrace))
819 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000820 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000821 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000822
Daniel Jasper4b866272013-02-01 11:00:45 +0000823 /// \brief Returns \c true, if a line break after \p State is mandatory.
824 bool mustBreak(const LineState &State) {
825 if (State.NextToken->MustBreakBefore)
826 return true;
827 if (State.NextToken->is(tok::r_brace) &&
828 State.Stack.back().BreakBeforeClosingBrace)
829 return true;
830 if (State.NextToken->Parent->is(tok::semi) &&
831 State.LineContainsContinuedForLoopSection)
832 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000833 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000834 State.NextToken->is(tok::question) ||
835 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000836 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000837 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000838 State.NextToken->isNot(tok::r_paren) &&
839 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000840 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000841 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
842 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000843 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000844 State.NextToken->LongestObjCSelectorName == 0 &&
845 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000846 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000847 if ((State.NextToken->Type == TT_CtorInitializerColon ||
848 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000849 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000850 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000851 if (State.NextToken->Type == TT_InlineASMColon)
852 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000853 // This prevents breaks like:
854 // ...
855 // SomeParameter, OtherParameter).DoSomething(
856 // ...
857 // As they hide "DoSomething" and generally bad for readability.
858 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
859 getRemainingLength(State) + State.Column > getColumnLimit() &&
860 State.ParenLevel < State.StartOfLineLevel)
861 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000862 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000863 }
864
Daniel Jasper9b334242013-03-15 14:57:30 +0000865 // Returns the total number of columns required for the remaining tokens.
866 unsigned getRemainingLength(const LineState &State) {
867 if (State.NextToken && State.NextToken->Parent)
868 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
869 return 0;
870 }
871
Daniel Jasperf7935112012-12-03 18:12:45 +0000872 FormatStyle Style;
873 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000874 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000875 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000877 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000878
879 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
880 QueueType Queue;
881 // Increasing count of \c StateNode items we have created. This is used
882 // to create a deterministic order independent of the container.
883 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000884};
885
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000886class LexerBasedFormatTokenSource : public FormatTokenSource {
887public:
888 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000889 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000890 IdentTable(Lex.getLangOpts()) {
891 Lex.SetKeepWhitespaceMode(true);
892 }
893
894 virtual FormatToken getNextToken() {
895 if (GreaterStashed) {
896 FormatTok.NewlinesBefore = 0;
897 FormatTok.WhiteSpaceStart =
898 FormatTok.Tok.getLocation().getLocWithOffset(1);
899 FormatTok.WhiteSpaceLength = 0;
900 GreaterStashed = false;
901 return FormatTok;
902 }
903
904 FormatTok = FormatToken();
905 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000906 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000907 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000908 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
909 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000910
911 // Consume and record whitespace until we find a significant token.
912 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000913 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +0000914 if (Newlines > 0)
915 FormatTok.LastNewlineOffset =
916 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +0000917 unsigned EscapedNewlines = Text.count("\\\n");
918 FormatTok.NewlinesBefore += Newlines;
919 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000920 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
921
922 if (FormatTok.Tok.is(tok::eof))
923 return FormatTok;
924 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000925 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000926 }
Manuel Klimekef920692013-01-07 07:56:50 +0000927
928 // Now FormatTok is the next non-whitespace token.
929 FormatTok.TokenLength = Text.size();
930
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000931 if (FormatTok.Tok.is(tok::comment)) {
932 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
933 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
934 }
935
Manuel Klimek1abf7892013-01-04 23:34:14 +0000936 // In case the token starts with escaped newlines, we want to
937 // take them into account as whitespace - this pattern is quite frequent
938 // in macro definitions.
939 // FIXME: What do we want to do with other escaped spaces, and escaped
940 // spaces or newlines in the middle of tokens?
941 // FIXME: Add a more explicit test.
942 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000943 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000944 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000945 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000946 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000947 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000948 }
949
950 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000951 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000952 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000953 FormatTok.Tok.setKind(Info.getTokenID());
954 }
955
956 if (FormatTok.Tok.is(tok::greatergreater)) {
957 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +0000958 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000959 GreaterStashed = true;
960 }
961
962 return FormatTok;
963 }
964
Nico Weber29f9dea2013-02-11 15:32:15 +0000965 IdentifierTable &getIdentTable() { return IdentTable; }
966
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000967private:
968 FormatToken FormatTok;
969 bool GreaterStashed;
970 Lexer &Lex;
971 SourceManager &SourceMgr;
972 IdentifierTable IdentTable;
973
974 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000975 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000976 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
977 Tok.getLength());
978 }
979};
980
Daniel Jasperf7935112012-12-03 18:12:45 +0000981class Formatter : public UnwrappedLineConsumer {
982public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000983 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
984 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000985 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000986 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000987 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000988
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000989 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000990
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000991 tooling::Replacements format() {
992 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
993 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000994 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000995 unsigned PreviousEndOfLineColumn = 0;
996 TokenAnnotator Annotator(Style, SourceMgr, Lex,
997 Tokens.getIdentTable().get("in"));
998 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
999 Annotator.annotate(AnnotatedLines[i]);
1000 }
1001 deriveLocalStyle();
1002 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1003 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1004 }
Daniel Jasperb67cc422013-04-09 17:46:55 +00001005
1006 // Adapt level to the next line if this is a comment.
1007 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001008 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001009 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1010 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1011 AnnotatedLines[i].First.Children.empty())
1012 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1013 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001014 NextNoneCommentLine =
1015 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1016 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001017 }
1018
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001019 std::vector<int> IndentForLevel;
1020 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001021 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001022 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1023 E = AnnotatedLines.end();
1024 I != E; ++I) {
1025 const AnnotatedLine &TheLine = *I;
1026 const FormatToken &FirstTok = TheLine.First.FormatTok;
1027 int Offset = getIndentOffset(TheLine.First);
1028 while (IndentForLevel.size() <= TheLine.Level)
1029 IndentForLevel.push_back(-1);
1030 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001031 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001032 if (TheLine.First.is(tok::eof)) {
1033 if (PreviousLineWasTouched) {
1034 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1035 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001036 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001037 }
1038 } else if (TheLine.Type != LT_Invalid &&
1039 (WasMoved || touchesLine(TheLine))) {
1040 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1041 unsigned Indent = LevelIndent;
1042 if (static_cast<int>(Indent) + Offset >= 0)
1043 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001044 if (FirstTok.WhiteSpaceStart.isValid() &&
1045 // Insert a break even if there is a structural error in case where
1046 // we break apart a line consisting of multiple unwrapped lines.
1047 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001048 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1049 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001050 } else {
1051 Indent = LevelIndent =
1052 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001053 }
1054 tryFitMultipleLinesInOne(Indent, I, E);
1055 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001056 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001057 PreviousEndOfLineColumn =
1058 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1059 IndentForLevel[TheLine.Level] = LevelIndent;
1060 PreviousLineWasTouched = true;
1061 } else {
1062 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1063 unsigned Indent =
1064 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1065 unsigned LevelIndent = Indent;
1066 if (static_cast<int>(LevelIndent) - Offset >= 0)
1067 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001068 if (TheLine.First.isNot(tok::comment))
1069 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001070
1071 // Remove trailing whitespace of the previous line if it was touched.
1072 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001073 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1074 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001075 }
1076 // If we did not reformat this unwrapped line, the column at the end of
1077 // the last token is unchanged - thus, we can calculate the end of the
1078 // last token.
1079 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1080 PreviousEndOfLineColumn =
1081 SourceMgr.getSpellingColumnNumber(LastLoc) +
1082 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1083 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001084 if (TheLine.Last->is(tok::comment))
1085 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1086 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Daniel Jasper770eb7c2013-04-24 06:33:59 +00001087 else
1088 Whitespaces.alignComments();
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001089 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001090 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001091 }
1092 return Whitespaces.generateReplacements();
1093 }
1094
1095private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001096 void deriveLocalStyle() {
1097 unsigned CountBoundToVariable = 0;
1098 unsigned CountBoundToType = 0;
1099 bool HasCpp03IncompatibleFormat = false;
1100 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1101 if (AnnotatedLines[i].First.Children.empty())
1102 continue;
1103 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1104 while (!Tok->Children.empty()) {
1105 if (Tok->Type == TT_PointerOrReference) {
1106 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1107 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1108 if (SpacesBefore && !SpacesAfter)
1109 ++CountBoundToVariable;
1110 else if (!SpacesBefore && SpacesAfter)
1111 ++CountBoundToType;
1112 }
1113
Daniel Jasper400adc62013-02-08 15:28:42 +00001114 if (Tok->Type == TT_TemplateCloser &&
1115 Tok->Parent->Type == TT_TemplateCloser &&
1116 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001117 HasCpp03IncompatibleFormat = true;
1118 Tok = &Tok->Children[0];
1119 }
1120 }
1121 if (Style.DerivePointerBinding) {
1122 if (CountBoundToType > CountBoundToVariable)
1123 Style.PointerBindsToType = true;
1124 else if (CountBoundToType < CountBoundToVariable)
1125 Style.PointerBindsToType = false;
1126 }
1127 if (Style.Standard == FormatStyle::LS_Auto) {
1128 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1129 : FormatStyle::LS_Cpp03;
1130 }
1131 }
1132
Manuel Klimekb95f5452013-02-08 17:38:27 +00001133 /// \brief Get the indent of \p Level from \p IndentForLevel.
1134 ///
1135 /// \p IndentForLevel must contain the indent for the level \c l
1136 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1137 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001138 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001139 if (IndentForLevel[Level] != -1)
1140 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001141 if (Level == 0)
1142 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001143 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001144 }
1145
1146 /// \brief Get the offset of the line relatively to the level.
1147 ///
1148 /// For example, 'public:' labels in classes are offset by 1 or 2
1149 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001150 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001151 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001152 return Style.AccessModifierOffset;
1153 return 0;
1154 }
1155
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001156 /// \brief Tries to merge lines into one.
1157 ///
1158 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1159 /// if possible; note that \c I will be incremented when lines are merged.
1160 ///
1161 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001162 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001163 std::vector<AnnotatedLine>::iterator &I,
1164 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001165 // We can never merge stuff if there are trailing line comments.
1166 if (I->Last->Type == TT_LineComment)
1167 return;
1168
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001169 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001170 // If we already exceed the column limit, we set 'Limit' to 0. The different
1171 // tryMerge..() functions can then decide whether to still do merging.
1172 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001173
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001174 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001175 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001176
Daniel Jasper25837aa2013-01-14 14:14:23 +00001177 if (I->Last->is(tok::l_brace)) {
1178 tryMergeSimpleBlock(I, E, Limit);
1179 } else if (I->First.is(tok::kw_if)) {
1180 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001181 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1182 I->First.FormatTok.IsFirst)) {
1183 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001184 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001185 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001186 }
1187
Daniel Jasper39825ea2013-01-14 15:40:57 +00001188 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1189 std::vector<AnnotatedLine>::iterator E,
1190 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001191 if (Limit == 0)
1192 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001193 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001194 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1195 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001196 if (I + 2 != E && (I + 2)->InPPDirective &&
1197 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1198 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001199 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001200 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001201 join(Line, *(++I));
1202 }
1203
Daniel Jasper25837aa2013-01-14 14:14:23 +00001204 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1205 std::vector<AnnotatedLine>::iterator E,
1206 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001207 if (Limit == 0)
1208 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001209 if (!Style.AllowShortIfStatementsOnASingleLine)
1210 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001211 if ((I + 1)->InPPDirective != I->InPPDirective ||
1212 ((I + 1)->InPPDirective &&
1213 (I + 1)->First.FormatTok.HasUnescapedNewline))
1214 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001215 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001216 if (Line.Last->isNot(tok::r_paren))
1217 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001218 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001219 return;
1220 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1221 return;
1222 // Only inline simple if's (no nested if or else).
1223 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1224 return;
1225 join(Line, *(++I));
1226 }
1227
1228 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001229 std::vector<AnnotatedLine>::iterator E,
1230 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001231 // First, check that the current line allows merging. This is the case if
1232 // we're not in a control flow statement and the last token is an opening
1233 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001234 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001235 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1236 tok::kw_else, tok::kw_try, tok::kw_catch,
1237 tok::kw_for,
1238 // This gets rid of all ObjC @ keywords and methods.
1239 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001240 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001241
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001242 AnnotatedToken *Tok = &(I + 1)->First;
1243 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001244 !Tok->MustBreakBefore) {
1245 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001246 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001247 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001248 join(Line, *(I + 1));
1249 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001250 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001251 // Check that we still have three lines and they fit into the limit.
1252 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1253 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001254 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001255
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001256 // Second, check that the next line does not contain any braces - if it
1257 // does, readability declines when putting it into a single line.
1258 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1259 return;
1260 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001261 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001262 return;
1263 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1264 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001265
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001266 // Last, check that the third line contains a single closing brace.
1267 Tok = &(I + 2)->First;
1268 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1269 Tok->MustBreakBefore)
1270 return;
1271
1272 join(Line, *(I + 1));
1273 join(Line, *(I + 2));
1274 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001275 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001276 }
1277
1278 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1279 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001280 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1281 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001282 }
1283
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001284 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001285 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001286 A.Last->Children.push_back(B.First);
1287 while (!A.Last->Children.empty()) {
1288 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001289 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001290 A.Last = &A.Last->Children[0];
1291 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001292 }
1293
Daniel Jasper97b89482013-03-13 07:49:51 +00001294 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001295 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1296 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1297 Ranges[i].getBegin()) &&
1298 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1299 Range.getBegin()))
1300 return true;
1301 }
1302 return false;
1303 }
1304
1305 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001306 const FormatToken *First = &TheLine.First.FormatTok;
1307 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001308 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001309 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1310 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001311 return touchesRanges(LineRange);
1312 }
1313
1314 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1315 const FormatToken *First = &TheLine.First.FormatTok;
1316 CharSourceRange LineRange = CharSourceRange::getCharRange(
1317 First->WhiteSpaceStart,
1318 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1319 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001320 }
1321
1322 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001323 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001324 }
1325
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001326 /// \brief Add a new line and the required indent before the first Token
1327 /// of the \c UnwrappedLine if there was no structural parsing error.
1328 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001329 void formatFirstToken(const AnnotatedToken &RootToken,
1330 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001331 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001332 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001333
Daniel Jasperbbc84152013-01-29 11:27:30 +00001334 unsigned Newlines =
1335 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001336 if (Newlines == 0 && !Tok.IsFirst)
1337 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001338
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001339 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001340 // Insert extra new line before access specifiers.
1341 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1342 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1343 ++Newlines;
1344
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001345 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001346 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001347 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001348 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001349 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001350 }
1351
Alexander Kornienko116ba682013-01-14 11:34:14 +00001352 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001353 FormatStyle Style;
1354 Lexer &Lex;
1355 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001356 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001357 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001358 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001359};
1360
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001361tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1362 SourceManager &SourceMgr,
1363 std::vector<CharSourceRange> Ranges,
1364 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001365 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001366 OwningPtr<DiagnosticConsumer> DiagPrinter;
1367 if (DiagClient == 0) {
1368 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1369 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1370 DiagClient = DiagPrinter.get();
1371 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001372 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001373 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001374 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001375 Diagnostics.setSourceManager(&SourceMgr);
1376 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001377 return formatter.format();
1378}
1379
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001380LangOptions getFormattingLangOpts() {
1381 LangOptions LangOpts;
1382 LangOpts.CPlusPlus = 1;
1383 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001384 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001385 LangOpts.Bool = 1;
1386 LangOpts.ObjC1 = 1;
1387 LangOpts.ObjC2 = 1;
1388 return LangOpts;
1389}
1390
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001391} // namespace format
1392} // namespace clang