blob: f93509e18c31976023d2759c1e55243dc57c05e6 [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 }
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000409 if (Current.isOneOf(tok::period, tok::arrow))
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000410 State.Stack.back().BreakBeforeParameter = true;
411
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000412 // If we break after {, we should also break before the corresponding }.
413 if (Previous.is(tok::l_brace))
414 State.Stack.back().BreakBeforeClosingBrace = true;
415
416 if (State.Stack.back().AvoidBinPacking) {
417 // If we are breaking after '(', '{', '<', this is not bin packing
418 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000419 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000420 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
421 Line.MustBeDeclaration))
422 State.Stack.back().BreakBeforeParameter = true;
423 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000424 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000425 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000426 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
427 State.Stack.back().VariablePos == 0) {
428 State.Stack.back().VariablePos = State.Column;
429 // Move over * and & if they are bound to the variable name.
430 const AnnotatedToken *Tok = &Previous;
431 while (Tok &&
432 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
433 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
434 if (Tok->SpacesRequiredBefore != 0)
435 break;
436 Tok = Tok->Parent;
437 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000438 if (Previous.PartOfMultiVariableDeclStmt)
439 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
440 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000441
Daniel Jaspereef30492013-02-11 12:36:37 +0000442 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000443
Daniel Jasperf7935112012-12-03 18:12:45 +0000444 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000445 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000446
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000447 if (Current.Type == TT_ObjCSelectorName &&
448 State.Stack.back().ColonPos == 0) {
449 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000450 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000451 State.Stack.back().ColonPos =
452 State.Stack.back().Indent + Current.LongestObjCSelectorName;
453 else
454 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000455 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000456 }
457
Daniel Jasperc04baae2013-04-10 09:49:49 +0000458 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000459 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000460 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000461 if (Previous.is(tok::comma) && !Current.isTrailingComment())
Daniel Jasper400adc62013-02-08 15:28:42 +0000462 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000463
Daniel Jaspere9de2602012-12-06 09:56:08 +0000464 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000465 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000466 // Treat the condition inside an if as if it was a second function
467 // parameter, i.e. let nested calls have an indent of 4.
468 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000469 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000470 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000471 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000472 Previous.Type == TT_ConditionalExpr ||
473 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000474 getPrecedence(Previous) != prec::Assignment)
475 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000476 else if (Previous.Type == TT_InheritanceColon)
477 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000478 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000479 // If this function has multiple parameters, indent nested calls from
480 // the start of the first parameter.
481 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000482 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000483
Manuel Klimek1998ea22013-02-20 10:15:13 +0000484 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000485 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000486
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000487 /// \brief Mark the next token as consumed in \p State and modify its stacks
488 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000489 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000490 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000491 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000492
Daniel Jaspereead02b2013-02-14 08:42:54 +0000493 if (Current.Type == TT_InheritanceColon)
494 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000495 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
496 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000497 if (Current.is(tok::question))
498 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000499 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000500 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
501 State.Stack.back().StartOfFunctionCall =
502 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000503 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000504 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000505 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
506 State.Stack.back().AvoidBinPacking = true;
507 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000508 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000509
Daniel Jasper6bee6822013-04-08 20:33:42 +0000510 // If return returns a binary expression, align after it.
511 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
512 State.Stack.back().LastSpace = State.Column + 7;
513
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000514 // In ObjC method declaration we align on the ":" of parameters, but we need
515 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000516 if (Current.Type == TT_ObjCMethodSpecifier)
517 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000518
Daniel Jasper400adc62013-02-08 15:28:42 +0000519 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000520 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
521 // Don't add extra indentation for the first fake parenthesis after
522 // 'return', assignements or opening <({[. The indentation for these cases
523 // is special cased.
524 bool SkipFirstExtraIndent =
525 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000526 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000527 getPrecedence(*Previous) == prec::Assignment));
528 for (SmallVector<prec::Level, 4>::const_reverse_iterator
529 I = Current.FakeLParens.rbegin(),
530 E = Current.FakeLParens.rend();
531 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000532 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000533 NewParenState.Indent =
534 std::max(std::max(State.Column, NewParenState.Indent),
535 State.Stack.back().LastSpace);
536
537 // Always indent conditional expressions. Never indent expression where
538 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
539 // prec::Assignment) as those have different indentation rules. Indent
540 // other expression, unless the indentation needs to be skipped.
541 if (*I == prec::Conditional ||
542 (!SkipFirstExtraIndent && *I > prec::Assignment))
543 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000544 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000545 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000546 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000547 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000548 }
549
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000550 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000551 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000552 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000553 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000554 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000555 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000556 NewIndent = 2 + State.Stack.back().LastSpace;
557 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000558 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000559 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
560 State.Stack.back().StartOfFunctionCall);
Daniel Jasperead41b62013-02-28 09:39:12 +0000561 AvoidBinPacking =
562 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000563 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000564 State.Stack.push_back(
565 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
566 State.Stack.back().HasMultiParameterLine));
Daniel Jasper400adc62013-02-08 15:28:42 +0000567 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000568 }
569
Daniel Jasperacc33662013-02-08 08:22:00 +0000570 // If this '[' opens an ObjC call, determine whether all parameters fit into
571 // one line and put one per line if they don't.
572 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
573 Current.MatchingParen != NULL) {
574 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
575 State.Stack.back().BreakBeforeParameter = true;
576 }
577
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000578 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000579 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000580 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000581 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
582 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000583 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000584 --State.ParenLevel;
585 }
586
587 // Remove scopes created by fake parenthesis.
588 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000589 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000590 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000591 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000593
Manuel Klimek0c915712013-02-20 15:32:58 +0000594 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000595 State.StartOfStringLiteral = State.Column;
596 } else if (Current.isNot(tok::comment)) {
597 State.StartOfStringLiteral = 0;
598 }
599
Manuel Klimek1998ea22013-02-20 10:15:13 +0000600 State.Column += Current.FormatTok.TokenLength;
601
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 if (State.NextToken->Children.empty())
603 State.NextToken = NULL;
604 else
605 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000606
Manuel Klimek1998ea22013-02-20 10:15:13 +0000607 return breakProtrudingToken(Current, State, DryRun);
608 }
609
610 /// \brief If the current token sticks out over the end of the line, break
611 /// it if possible.
612 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
613 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000614 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000615 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000616 if (Current.is(tok::string_literal)) {
617 // Only break up default narrow strings.
618 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
619 if (!LiteralData || *LiteralData != '"')
620 return 0;
621
622 Token.reset(new BreakableStringLiteral(Current.FormatTok, StartColumn));
623 } else if (Current.Type == TT_BlockComment) {
624 BreakableBlockComment *BBC =
625 new BreakableBlockComment(SourceMgr, Current, StartColumn);
626 if (!DryRun)
627 BBC->alignLines(Whitespaces);
628 Token.reset(BBC);
629 } else {
630 return 0;
631 }
632
633 if (Token->getPrefixLength() + Token->getSuffixLength(0) >
634 getColumnLimit()) {
635 return 0;
636 }
637
638 bool BreakInserted = false;
639 unsigned Penalty = 0;
640 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
641 ++LineIndex) {
642 unsigned TokenLineSize = Token->getLineSize(LineIndex);
643 unsigned TailOffset = 0;
644 unsigned RemainingLength =
645 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
646 while (RemainingLength > getColumnLimit()) {
647 unsigned DecorationLength =
648 RemainingLength - (TokenLineSize - TailOffset);
649 if (DecorationLength + 1 > getColumnLimit()) {
650 // Can't reduce line length by splitting here.
651 break;
652 }
653 BreakableToken::Split Split =
654 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
655 if (Split.first == StringRef::npos)
656 break;
657 assert(Split.first != 0);
658 if (!DryRun) {
659 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
660 Whitespaces);
661 }
662 TailOffset += Split.first + Split.second;
663 unsigned OldRemainingLength = RemainingLength;
664 RemainingLength = Token->getLineLengthAfterSplit(LineIndex, TailOffset);
665 assert(RemainingLength < OldRemainingLength);
666 Penalty += Style.PenaltyExcessCharacter;
667 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000668 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000669 State.Column = RemainingLength;
670 if (!DryRun) {
671 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
672 }
673 }
674
675 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000676 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
677 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000678 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000679 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000680 return Penalty;
681 }
682
Daniel Jasper2df93312013-01-09 10:16:05 +0000683 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000684 // In preprocessor directives reserve two chars for trailing " \"
685 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000686 }
687
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000688 /// \brief An edge in the solution space from \c Previous->State to \c State,
689 /// inserting a newline dependent on the \c NewLine.
690 struct StateNode {
691 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000692 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000693 LineState State;
694 bool NewLine;
695 StateNode *Previous;
696 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000697
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000698 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
699 ///
700 /// In case of equal penalties, we want to prefer states that were inserted
701 /// first. During state generation we make sure that we insert states first
702 /// that break the line as late as possible.
703 typedef std::pair<unsigned, unsigned> OrderedPenalty;
704
705 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
706 /// \c State has the given \c OrderedPenalty.
707 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
708
709 /// \brief The BFS queue type.
710 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
711 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000712
713 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000715 /// This implements a variant of Dijkstra's algorithm on the graph that spans
716 /// the solution space (\c LineStates are the nodes). The algorithm tries to
717 /// find the shortest path (the one with lowest penalty) from \p InitialState
718 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000719 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000720 std::set<LineState> Seen;
721
Daniel Jasper4b866272013-02-01 11:00:45 +0000722 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000723 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000724 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
725 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
726 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000727
728 // While not empty, take first element and follow edges.
729 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000730 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000731 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000732 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000733 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000734 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000735 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000736 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000737
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000738 if (!Seen.insert(Node->State).second)
739 // State already examined with lower penalty.
740 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000741
Manuel Klimekaf491072013-02-13 10:54:19 +0000742 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
743 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000744 }
745
746 if (Queue.empty())
747 // We were unable to find a solution, do nothing.
748 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000749 return 0;
750
Daniel Jasper4b866272013-02-01 11:00:45 +0000751 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000752 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000753 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000754
Daniel Jasper4b866272013-02-01 11:00:45 +0000755 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000756 return Queue.top().second->State.Column;
757 }
758
759 void reconstructPath(LineState &State, StateNode *Current) {
760 // FIXME: This recursive implementation limits the possible number
761 // of tokens per line if compiled into a binary with small stack space.
762 // To become more independent of stack frame limitations we would need
763 // to also change the TokenAnnotator.
764 if (Current->Previous == NULL)
765 return;
766 reconstructPath(State, Current->Previous);
767 DEBUG({
768 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000769 llvm::errs()
770 << "Penalty for splitting before "
771 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
772 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000773 }
774 });
775 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000776 }
777
Manuel Klimekaf491072013-02-13 10:54:19 +0000778 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000779 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000780 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000781 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000782 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
783 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000784 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000785 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000786 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000787 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000788 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000789 Penalty += PreviousNode->State.NextToken->SplitPenalty;
790
791 StateNode *Node = new (Allocator.Allocate())
792 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000793 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000794 if (Node->State.Column > getColumnLimit()) {
795 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000796 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000797 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000798
799 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
800 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000801 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000802
Daniel Jasper4b866272013-02-01 11:00:45 +0000803 /// \brief Returns \c true, if a line break after \p State is allowed.
804 bool canBreak(const LineState &State) {
805 if (!State.NextToken->CanBreakBefore &&
806 !(State.NextToken->is(tok::r_brace) &&
807 State.Stack.back().BreakBeforeClosingBrace))
808 return false;
809 // Trying to insert a parameter on a new line if there are already more than
810 // one parameter on the current line is bin packing.
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000811 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper4b866272013-02-01 11:00:45 +0000812 State.Stack.back().AvoidBinPacking)
813 return false;
814 return true;
815 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000816
Daniel Jasper4b866272013-02-01 11:00:45 +0000817 /// \brief Returns \c true, if a line break after \p State is mandatory.
818 bool mustBreak(const LineState &State) {
819 if (State.NextToken->MustBreakBefore)
820 return true;
821 if (State.NextToken->is(tok::r_brace) &&
822 State.Stack.back().BreakBeforeClosingBrace)
823 return true;
824 if (State.NextToken->Parent->is(tok::semi) &&
825 State.LineContainsContinuedForLoopSection)
826 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000827 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000828 State.NextToken->is(tok::question) ||
829 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000830 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000831 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000832 State.NextToken->isNot(tok::r_paren) &&
833 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000834 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000835 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
836 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000837 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000838 State.NextToken->LongestObjCSelectorName == 0 &&
839 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000840 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000841 if ((State.NextToken->Type == TT_CtorInitializerColon ||
842 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000843 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000844 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000845 if (State.NextToken->Type == TT_InlineASMColon)
846 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000847 // This prevents breaks like:
848 // ...
849 // SomeParameter, OtherParameter).DoSomething(
850 // ...
851 // As they hide "DoSomething" and generally bad for readability.
852 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
853 getRemainingLength(State) + State.Column > getColumnLimit() &&
854 State.ParenLevel < State.StartOfLineLevel)
855 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000856 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000857 }
858
Daniel Jasper9b334242013-03-15 14:57:30 +0000859 // Returns the total number of columns required for the remaining tokens.
860 unsigned getRemainingLength(const LineState &State) {
861 if (State.NextToken && State.NextToken->Parent)
862 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
863 return 0;
864 }
865
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 FormatStyle Style;
867 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000868 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000869 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000871 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000872
873 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
874 QueueType Queue;
875 // Increasing count of \c StateNode items we have created. This is used
876 // to create a deterministic order independent of the container.
877 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000878};
879
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000880class LexerBasedFormatTokenSource : public FormatTokenSource {
881public:
882 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000883 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000884 IdentTable(Lex.getLangOpts()) {
885 Lex.SetKeepWhitespaceMode(true);
886 }
887
888 virtual FormatToken getNextToken() {
889 if (GreaterStashed) {
890 FormatTok.NewlinesBefore = 0;
891 FormatTok.WhiteSpaceStart =
892 FormatTok.Tok.getLocation().getLocWithOffset(1);
893 FormatTok.WhiteSpaceLength = 0;
894 GreaterStashed = false;
895 return FormatTok;
896 }
897
898 FormatTok = FormatToken();
899 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000900 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000901 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000902 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
903 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000904
905 // Consume and record whitespace until we find a significant token.
906 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000907 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +0000908 if (Newlines > 0)
909 FormatTok.LastNewlineOffset =
910 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +0000911 unsigned EscapedNewlines = Text.count("\\\n");
912 FormatTok.NewlinesBefore += Newlines;
913 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000914 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
915
916 if (FormatTok.Tok.is(tok::eof))
917 return FormatTok;
918 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000919 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000920 }
Manuel Klimekef920692013-01-07 07:56:50 +0000921
922 // Now FormatTok is the next non-whitespace token.
923 FormatTok.TokenLength = Text.size();
924
Manuel Klimek1abf7892013-01-04 23:34:14 +0000925 // In case the token starts with escaped newlines, we want to
926 // take them into account as whitespace - this pattern is quite frequent
927 // in macro definitions.
928 // FIXME: What do we want to do with other escaped spaces, and escaped
929 // spaces or newlines in the middle of tokens?
930 // FIXME: Add a more explicit test.
931 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000932 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000933 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000934 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000935 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000936 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000937 }
938
939 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000940 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000941 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000942 FormatTok.Tok.setKind(Info.getTokenID());
943 }
944
945 if (FormatTok.Tok.is(tok::greatergreater)) {
946 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +0000947 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000948 GreaterStashed = true;
949 }
950
Daniel Jasper3324cbe2013-03-01 16:45:59 +0000951 // If we reformat comments, we remove trailing whitespace. Update the length
952 // accordingly.
953 if (FormatTok.Tok.is(tok::comment))
954 FormatTok.TokenLength = Text.rtrim().size();
955
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000956 return FormatTok;
957 }
958
Nico Weber29f9dea2013-02-11 15:32:15 +0000959 IdentifierTable &getIdentTable() { return IdentTable; }
960
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000961private:
962 FormatToken FormatTok;
963 bool GreaterStashed;
964 Lexer &Lex;
965 SourceManager &SourceMgr;
966 IdentifierTable IdentTable;
967
968 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000969 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000970 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
971 Tok.getLength());
972 }
973};
974
Daniel Jasperf7935112012-12-03 18:12:45 +0000975class Formatter : public UnwrappedLineConsumer {
976public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000977 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
978 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000979 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000980 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000981 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000982
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000983 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000984
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000985 tooling::Replacements format() {
986 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
987 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000988 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000989 unsigned PreviousEndOfLineColumn = 0;
990 TokenAnnotator Annotator(Style, SourceMgr, Lex,
991 Tokens.getIdentTable().get("in"));
992 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
993 Annotator.annotate(AnnotatedLines[i]);
994 }
995 deriveLocalStyle();
996 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
997 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
998 }
Daniel Jasperb67cc422013-04-09 17:46:55 +0000999
1000 // Adapt level to the next line if this is a comment.
1001 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +00001002 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001003 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1004 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1005 AnnotatedLines[i].First.Children.empty())
1006 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1007 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001008 NextNoneCommentLine =
1009 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1010 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001011 }
1012
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001013 std::vector<int> IndentForLevel;
1014 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001015 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001016 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1017 E = AnnotatedLines.end();
1018 I != E; ++I) {
1019 const AnnotatedLine &TheLine = *I;
1020 const FormatToken &FirstTok = TheLine.First.FormatTok;
1021 int Offset = getIndentOffset(TheLine.First);
1022 while (IndentForLevel.size() <= TheLine.Level)
1023 IndentForLevel.push_back(-1);
1024 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001025 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001026 if (TheLine.First.is(tok::eof)) {
1027 if (PreviousLineWasTouched) {
1028 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1029 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001030 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001031 }
1032 } else if (TheLine.Type != LT_Invalid &&
1033 (WasMoved || touchesLine(TheLine))) {
1034 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1035 unsigned Indent = LevelIndent;
1036 if (static_cast<int>(Indent) + Offset >= 0)
1037 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001038 if (FirstTok.WhiteSpaceStart.isValid() &&
1039 // Insert a break even if there is a structural error in case where
1040 // we break apart a line consisting of multiple unwrapped lines.
1041 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001042 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1043 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001044 } else {
1045 Indent = LevelIndent =
1046 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001047 }
1048 tryFitMultipleLinesInOne(Indent, I, E);
1049 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001050 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001051 PreviousEndOfLineColumn =
1052 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1053 IndentForLevel[TheLine.Level] = LevelIndent;
1054 PreviousLineWasTouched = true;
1055 } else {
1056 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1057 unsigned Indent =
1058 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1059 unsigned LevelIndent = Indent;
1060 if (static_cast<int>(LevelIndent) - Offset >= 0)
1061 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001062 if (TheLine.First.isNot(tok::comment))
1063 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001064
1065 // Remove trailing whitespace of the previous line if it was touched.
1066 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001067 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1068 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001069 }
1070 // If we did not reformat this unwrapped line, the column at the end of
1071 // the last token is unchanged - thus, we can calculate the end of the
1072 // last token.
1073 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1074 PreviousEndOfLineColumn =
1075 SourceMgr.getSpellingColumnNumber(LastLoc) +
1076 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1077 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001078 if (TheLine.Last->is(tok::comment))
1079 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1080 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001081 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001082 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001083 }
1084 return Whitespaces.generateReplacements();
1085 }
1086
1087private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001088 void deriveLocalStyle() {
1089 unsigned CountBoundToVariable = 0;
1090 unsigned CountBoundToType = 0;
1091 bool HasCpp03IncompatibleFormat = false;
1092 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1093 if (AnnotatedLines[i].First.Children.empty())
1094 continue;
1095 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1096 while (!Tok->Children.empty()) {
1097 if (Tok->Type == TT_PointerOrReference) {
1098 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1099 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1100 if (SpacesBefore && !SpacesAfter)
1101 ++CountBoundToVariable;
1102 else if (!SpacesBefore && SpacesAfter)
1103 ++CountBoundToType;
1104 }
1105
Daniel Jasper400adc62013-02-08 15:28:42 +00001106 if (Tok->Type == TT_TemplateCloser &&
1107 Tok->Parent->Type == TT_TemplateCloser &&
1108 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001109 HasCpp03IncompatibleFormat = true;
1110 Tok = &Tok->Children[0];
1111 }
1112 }
1113 if (Style.DerivePointerBinding) {
1114 if (CountBoundToType > CountBoundToVariable)
1115 Style.PointerBindsToType = true;
1116 else if (CountBoundToType < CountBoundToVariable)
1117 Style.PointerBindsToType = false;
1118 }
1119 if (Style.Standard == FormatStyle::LS_Auto) {
1120 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1121 : FormatStyle::LS_Cpp03;
1122 }
1123 }
1124
Manuel Klimekb95f5452013-02-08 17:38:27 +00001125 /// \brief Get the indent of \p Level from \p IndentForLevel.
1126 ///
1127 /// \p IndentForLevel must contain the indent for the level \c l
1128 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1129 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001130 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001131 if (IndentForLevel[Level] != -1)
1132 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001133 if (Level == 0)
1134 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001135 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001136 }
1137
1138 /// \brief Get the offset of the line relatively to the level.
1139 ///
1140 /// For example, 'public:' labels in classes are offset by 1 or 2
1141 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001142 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001143 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001144 return Style.AccessModifierOffset;
1145 return 0;
1146 }
1147
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001148 /// \brief Tries to merge lines into one.
1149 ///
1150 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1151 /// if possible; note that \c I will be incremented when lines are merged.
1152 ///
1153 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001154 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001155 std::vector<AnnotatedLine>::iterator &I,
1156 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001157 // We can never merge stuff if there are trailing line comments.
1158 if (I->Last->Type == TT_LineComment)
1159 return;
1160
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001161 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001162 // If we already exceed the column limit, we set 'Limit' to 0. The different
1163 // tryMerge..() functions can then decide whether to still do merging.
1164 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001165
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001166 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001167 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001168
Daniel Jasper25837aa2013-01-14 14:14:23 +00001169 if (I->Last->is(tok::l_brace)) {
1170 tryMergeSimpleBlock(I, E, Limit);
1171 } else if (I->First.is(tok::kw_if)) {
1172 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001173 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1174 I->First.FormatTok.IsFirst)) {
1175 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001176 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001177 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001178 }
1179
Daniel Jasper39825ea2013-01-14 15:40:57 +00001180 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1181 std::vector<AnnotatedLine>::iterator E,
1182 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001183 if (Limit == 0)
1184 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001185 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001186 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1187 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001188 if (I + 2 != E && (I + 2)->InPPDirective &&
1189 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1190 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001191 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001192 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001193 join(Line, *(++I));
1194 }
1195
Daniel Jasper25837aa2013-01-14 14:14:23 +00001196 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1197 std::vector<AnnotatedLine>::iterator E,
1198 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001199 if (Limit == 0)
1200 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001201 if (!Style.AllowShortIfStatementsOnASingleLine)
1202 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001203 if ((I + 1)->InPPDirective != I->InPPDirective ||
1204 ((I + 1)->InPPDirective &&
1205 (I + 1)->First.FormatTok.HasUnescapedNewline))
1206 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001207 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001208 if (Line.Last->isNot(tok::r_paren))
1209 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001210 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001211 return;
1212 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1213 return;
1214 // Only inline simple if's (no nested if or else).
1215 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1216 return;
1217 join(Line, *(++I));
1218 }
1219
1220 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001221 std::vector<AnnotatedLine>::iterator E,
1222 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001223 // First, check that the current line allows merging. This is the case if
1224 // we're not in a control flow statement and the last token is an opening
1225 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001226 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001227 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1228 tok::kw_else, tok::kw_try, tok::kw_catch,
1229 tok::kw_for,
1230 // This gets rid of all ObjC @ keywords and methods.
1231 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001232 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001233
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001234 AnnotatedToken *Tok = &(I + 1)->First;
1235 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001236 !Tok->MustBreakBefore) {
1237 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001238 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001239 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001240 join(Line, *(I + 1));
1241 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001242 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001243 // Check that we still have three lines and they fit into the limit.
1244 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1245 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001246 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001247
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001248 // Second, check that the next line does not contain any braces - if it
1249 // does, readability declines when putting it into a single line.
1250 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1251 return;
1252 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001253 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001254 return;
1255 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1256 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001257
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001258 // Last, check that the third line contains a single closing brace.
1259 Tok = &(I + 2)->First;
1260 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1261 Tok->MustBreakBefore)
1262 return;
1263
1264 join(Line, *(I + 1));
1265 join(Line, *(I + 2));
1266 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001267 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001268 }
1269
1270 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1271 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001272 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1273 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001274 }
1275
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001276 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001277 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001278 A.Last->Children.push_back(B.First);
1279 while (!A.Last->Children.empty()) {
1280 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001281 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001282 A.Last = &A.Last->Children[0];
1283 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001284 }
1285
Daniel Jasper97b89482013-03-13 07:49:51 +00001286 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001287 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1288 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1289 Ranges[i].getBegin()) &&
1290 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1291 Range.getBegin()))
1292 return true;
1293 }
1294 return false;
1295 }
1296
1297 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001298 const FormatToken *First = &TheLine.First.FormatTok;
1299 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001300 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001301 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1302 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001303 return touchesRanges(LineRange);
1304 }
1305
1306 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1307 const FormatToken *First = &TheLine.First.FormatTok;
1308 CharSourceRange LineRange = CharSourceRange::getCharRange(
1309 First->WhiteSpaceStart,
1310 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1311 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001312 }
1313
1314 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001315 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001316 }
1317
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001318 /// \brief Add a new line and the required indent before the first Token
1319 /// of the \c UnwrappedLine if there was no structural parsing error.
1320 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001321 void formatFirstToken(const AnnotatedToken &RootToken,
1322 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001323 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001324 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001325
Daniel Jasperbbc84152013-01-29 11:27:30 +00001326 unsigned Newlines =
1327 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001328 if (Newlines == 0 && !Tok.IsFirst)
1329 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001330
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001331 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001332 // Insert extra new line before access specifiers.
1333 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1334 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1335 ++Newlines;
1336
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001337 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001338 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001339 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001340 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001341 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001342 }
1343
Alexander Kornienko116ba682013-01-14 11:34:14 +00001344 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001345 FormatStyle Style;
1346 Lexer &Lex;
1347 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001348 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001349 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001350 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001351};
1352
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001353tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1354 SourceManager &SourceMgr,
1355 std::vector<CharSourceRange> Ranges,
1356 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001357 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001358 OwningPtr<DiagnosticConsumer> DiagPrinter;
1359 if (DiagClient == 0) {
1360 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1361 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1362 DiagClient = DiagPrinter.get();
1363 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001364 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001365 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001366 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001367 Diagnostics.setSourceManager(&SourceMgr);
1368 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001369 return formatter.format();
1370}
1371
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001372LangOptions getFormattingLangOpts() {
1373 LangOptions LangOpts;
1374 LangOpts.CPlusPlus = 1;
1375 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001376 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001377 LangOpts.Bool = 1;
1378 LangOpts.ObjC1 = 1;
1379 LangOpts.ObjC2 = 1;
1380 return LangOpts;
1381}
1382
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001383} // namespace format
1384} // namespace clang