blob: a847d4ef9bd5773c30bf09e83e710086950b8599 [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
Daniel Jasperbac016b2012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Manuel Klimekca547db2013-01-16 14:55:28 +000016#define DEBUG_TYPE "format-formatter"
17
Alexander Kornienko70ce7882013-04-15 14:28:00 +000018#include "BreakableToken.h"
Daniel Jasper32d28ee2013-01-29 21:01:14 +000019#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Alexander Kornienko70ce7882013-04-15 14:28:00 +000021#include "WhitespaceManager.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Alexander Kornienko5262dd92013-03-27 11:52:18 +000028#include "llvm/ADT/STLExtras.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000029#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000030#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000031#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000032#include <string>
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperbac016b2012-12-03 18:12:45 +000037FormatStyle getLLVMStyle() {
38 FormatStyle LLVMStyle;
39 LLVMStyle.ColumnLimit = 80;
40 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000041 LLVMStyle.PointerBindsToType = false;
42 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000043 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000044 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000045 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000046 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000047 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000048 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000049 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000050 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000051 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000052 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000053 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
Daniel Jasperbac016b2012-12-03 18:12:45 +000054 return LLVMStyle;
55}
56
57FormatStyle getGoogleStyle() {
58 FormatStyle GoogleStyle;
59 GoogleStyle.ColumnLimit = 80;
60 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000061 GoogleStyle.PointerBindsToType = true;
62 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000063 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000064 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000065 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000066 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000067 GoogleStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000068 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000069 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000070 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000071 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000072 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasper1407bee2013-04-11 14:29:13 +000073 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
Daniel Jasperbac016b2012-12-03 18:12:45 +000074 return GoogleStyle;
75}
76
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000077FormatStyle getChromiumStyle() {
78 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000079 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000080 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000081 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
82 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000083 return ChromiumStyle;
84}
85
Daniel Jasperce3d1a62013-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 Jasperbac016b2012-12-03 18:12:45 +000098class UnwrappedLineFormatter {
99public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000100 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000101 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000102 const AnnotatedToken &RootToken,
Manuel Klimek67d080d2013-04-12 14:13:36 +0000103 WhitespaceManager &Whitespaces)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000104 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000105 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000106 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000107
Manuel Klimekd4397b92013-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 Jaspera4d46212013-02-28 11:05:57 +0000112 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000113 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000114 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000115 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000116 State.NextToken = &RootToken;
Daniel Jasper6f21a982013-03-13 07:49:51 +0000117 State.Stack.push_back(
Daniel Jasper37911302013-04-02 14:33:13 +0000118 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
Daniel Jasper6f21a982013-03-13 07:49:51 +0000119 /*HasMultiParameterLine=*/ false));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000120 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000121 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000122 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000123 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000124
125 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000126 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000127
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000128 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-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 Jasper68ef0df2013-02-01 11:00:45 +0000134 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000135 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000136 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000137 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000138 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000139
Daniel Jasperce3d1a62013-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 Jasper68ef0df2013-02-01 11:00:45 +0000145 // Find best solution in solution space.
146 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000147 }
148
149private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000150 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
151 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000152 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
153 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000154 llvm::errs();
155 }
156
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000157 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000158 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
159 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000160 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
161 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000162 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper24849712013-03-01 16:48:32 +0000163 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
Daniel Jasper37911302013-04-02 14:33:13 +0000164 StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000165 CallContinuation(0), VariablePos(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000166
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167 /// \brief The position to which a specific parenthesis level needs to be
168 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000169 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000170
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000176 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000177
Daniel Jasper3b5943f2012-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 Jasper604eb4c2013-01-11 10:22:12 +0000182 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000183
Manuel Klimekc8c8a472013-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 Jasper604eb4c2013-01-11 10:22:12 +0000189 bool BreakBeforeClosingBrace;
190
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000191 /// \brief The column of a \c ? in a conditional expression;
192 unsigned QuestionColumn;
193
Daniel Jasperf343cab2013-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 Jasperce3d1a62013-02-08 08:22:00 +0000200 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000201
202 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000203 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000204
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000205 /// \brief The position of the colon in an ObjC method declaration/call.
206 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000207
Daniel Jasper24849712013-03-01 16:48:32 +0000208 /// \brief The start of the most recent function in a builder-type call.
209 unsigned StartOfFunctionCall;
210
Daniel Jasper37911302013-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 Jasper8ed9f2b2013-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 Jasper604eb4c2013-01-11 10:22:12 +0000224 bool operator<(const ParenState &Other) const {
225 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000226 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-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 Jasper7e9bf8c2013-01-11 11:37:55 +0000231 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
232 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000233 if (QuestionColumn != Other.QuestionColumn)
234 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000235 if (AvoidBinPacking != Other.AvoidBinPacking)
236 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000237 if (BreakBeforeParameter != Other.BreakBeforeParameter)
238 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000239 if (HasMultiParameterLine != Other.HasMultiParameterLine)
240 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000241 if (ColonPos != Other.ColonPos)
242 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000243 if (StartOfFunctionCall != Other.StartOfFunctionCall)
244 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasper37911302013-04-02 14:33:13 +0000245 if (NestedNameSpecifierContinuation !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000246 Other.NestedNameSpecifierContinuation)
Daniel Jasper37911302013-04-02 14:33:13 +0000247 return NestedNameSpecifierContinuation <
248 Other.NestedNameSpecifierContinuation;
249 if (CallContinuation != Other.CallContinuation)
250 return CallContinuation < Other.CallContinuation;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000251 if (VariablePos != Other.VariablePos)
252 return VariablePos < Other.VariablePos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000253 return false;
Daniel Jasper604eb4c2013-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 Jaspera324a0e2012-12-21 14:37:20 +0000267 /// \brief \c true if this line contains a continued for-loop section.
268 bool LineContainsContinuedForLoopSection;
269
Daniel Jasper29f123b2013-02-08 15:28:42 +0000270 /// \brief The level of nesting inside (), [], <> and {}.
271 unsigned ParenLevel;
272
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000273 /// \brief The \c ParenLevel at the start of this line.
274 unsigned StartOfLineLevel;
275
Manuel Klimekb56b6d12013-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 Jasper604eb4c2013-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 Jasperd7896702013-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 Jasperd7896702013-02-19 09:28:55 +0000290 if (LineContainsContinuedForLoopSection !=
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000291 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000292 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-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 Klimekb56b6d12013-02-20 15:25:48 +0000297 if (StartOfStringLiteral != Other.StartOfStringLiteral)
298 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000299 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000300 }
301 };
302
Daniel Jasper20409152012-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 Klimek8092a942013-02-20 10:15:13 +0000311 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000312 const AnnotatedToken &Current = *State.NextToken;
313 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000314
Daniel Jasper92f9faf2013-03-20 15:58:10 +0000315 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper68ef0df2013-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 Klimek8092a942013-02-20 10:15:13 +0000322 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000323 }
324
Daniel Jasper3776ef32013-04-03 07:21:51 +0000325 // If we are continuing an expression, we want to indent an extra 4 spaces.
326 unsigned ContinuationIndent =
Daniel Jasper37911302013-04-02 14:33:13 +0000327 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000328 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000329 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000330 if (Current.is(tok::r_brace)) {
331 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000332 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000333 State.StartOfStringLiteral != 0) {
334 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000335 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000336 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000337 State.Stack.back().FirstLessLess != 0) {
338 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasper37911302013-04-02 14:33:13 +0000339 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000340 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
341 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000342 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000343 } else {
344 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
345 }
Daniel Jasper37911302013-04-02 14:33:13 +0000346 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000347 if (State.Stack.back().CallContinuation == 0) {
348 State.Column = ContinuationIndent;
Daniel Jasper37911302013-04-02 14:33:13 +0000349 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000350 } else {
351 State.Column = State.Stack.back().CallContinuation;
352 }
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000353 } else if (Current.Type == TT_ConditionalExpr) {
354 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper8ed9f2b2013-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 Jasper3c08a812013-02-24 18:54:32 +0000358 } else if (Previous.ClosesTemplateDeclaration ||
359 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper37911302013-04-02 14:33:13 +0000360 State.Column = State.Stack.back().Indent;
Daniel Jasper63d7ced2013-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 Jasperbf71ba22013-04-08 20:33:42 +0000370 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasper37911302013-04-02 14:33:13 +0000371 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper3776ef32013-04-03 07:21:51 +0000372 State.Column = ContinuationIndent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000373 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000374 State.Column = State.Stack.back().Indent;
Daniel Jasper3776ef32013-04-03 07:21:51 +0000375 // Ensure that we fall back to indenting 4 spaces instead of just
376 // flushing continuations left.
Daniel Jasper37911302013-04-02 14:33:13 +0000377 if (State.Column == FirstIndent)
378 State.Column += 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000379 }
380
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000381 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000382 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000383 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jasper237d4c12013-02-23 21:01:55 +0000384 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000385 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000386
Manuel Klimek060143e2013-01-02 18:33:23 +0000387 if (!DryRun) {
Daniel Jasper1ef81d52013-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 Klimek060143e2013-01-02 18:33:23 +0000393 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000394 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000395 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000396 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000397 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienko052685c2013-03-19 17:41:36 +0000398 WhitespaceStartColumn);
Manuel Klimek060143e2013-01-02 18:33:23 +0000399 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000400
Daniel Jasper29f123b2013-02-08 15:28:42 +0000401 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000402 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000403
404 // Any break on this level means that the parent level has been broken
405 // and we need to avoid bin packing there.
406 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
407 State.Stack[i].BreakBeforeParameter = true;
408 }
Daniel Jasper01218ff2013-04-15 22:36:37 +0000409 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
410 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
411 !TokenBefore->opensScope())
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000412 State.Stack.back().BreakBeforeParameter = true;
413
Daniel Jasper237d4c12013-02-23 21:01:55 +0000414 // If we break after {, we should also break before the corresponding }.
415 if (Previous.is(tok::l_brace))
416 State.Stack.back().BreakBeforeClosingBrace = true;
417
418 if (State.Stack.back().AvoidBinPacking) {
419 // If we are breaking after '(', '{', '<', this is not bin packing
420 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000421 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000422 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
423 Line.MustBeDeclaration))
424 State.Stack.back().BreakBeforeParameter = true;
425 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000426 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000427 if (Current.is(tok::equal) &&
Daniel Jasperadc0f092013-04-05 09:38:50 +0000428 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
429 State.Stack.back().VariablePos == 0) {
430 State.Stack.back().VariablePos = State.Column;
431 // Move over * and & if they are bound to the variable name.
432 const AnnotatedToken *Tok = &Previous;
433 while (Tok &&
434 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
435 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
436 if (Tok->SpacesRequiredBefore != 0)
437 break;
438 Tok = Tok->Parent;
439 }
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000440 if (Previous.PartOfMultiVariableDeclStmt)
441 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
442 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000443
Daniel Jasper729a7432013-02-11 12:36:37 +0000444 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000445
Daniel Jasperbac016b2012-12-03 18:12:45 +0000446 if (!DryRun)
Alexander Kornienko052685c2013-03-19 17:41:36 +0000447 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper20409152012-12-04 14:54:30 +0000448
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000449 if (Current.Type == TT_ObjCSelectorName &&
450 State.Stack.back().ColonPos == 0) {
451 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000452 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000453 State.Stack.back().ColonPos =
454 State.Stack.back().Indent + Current.LongestObjCSelectorName;
455 else
456 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000457 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000458 }
459
Daniel Jasperac3223e2013-04-10 09:49:49 +0000460 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000461 Current.Type != TT_LineComment)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000462 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000463 if (Previous.is(tok::comma) && !Current.isTrailingComment())
Daniel Jasper29f123b2013-02-08 15:28:42 +0000464 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000465
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000466 State.Column += Spaces;
Daniel Jasper8ed9f2b2013-04-03 13:36:17 +0000467 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000468 // Treat the condition inside an if as if it was a second function
469 // parameter, i.e. let nested calls have an indent of 4.
470 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperf9955d32013-03-20 12:37:50 +0000471 else if (Previous.is(tok::comma))
Daniel Jaspere438bac2013-01-23 20:41:06 +0000472 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000473 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000474 Previous.Type == TT_ConditionalExpr ||
475 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000476 getPrecedence(Previous) != prec::Assignment)
477 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000478 else if (Previous.Type == TT_InheritanceColon)
479 State.Stack.back().Indent = State.Column;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000480 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper986e17f2013-01-28 07:35:34 +0000481 // If this function has multiple parameters, indent nested calls from
482 // the start of the first parameter.
483 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000484 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000485
Manuel Klimek8092a942013-02-20 10:15:13 +0000486 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000487 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488
Daniel Jasper20409152012-12-04 14:54:30 +0000489 /// \brief Mark the next token as consumed in \p State and modify its stacks
490 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000491 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000492 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000493 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000494
Daniel Jasper6cabab42013-02-14 08:42:54 +0000495 if (Current.Type == TT_InheritanceColon)
496 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000497 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
498 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000499 if (Current.is(tok::question))
500 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000501 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasper24849712013-03-01 16:48:32 +0000502 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
503 State.Stack.back().StartOfFunctionCall =
504 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000505 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000506 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper7d812812013-02-21 15:00:29 +0000507 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
508 State.Stack.back().AvoidBinPacking = true;
509 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000510 }
Daniel Jasper3776ef32013-04-03 07:21:51 +0000511
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000512 // If return returns a binary expression, align after it.
513 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
514 State.Stack.back().LastSpace = State.Column + 7;
515
Daniel Jasper3776ef32013-04-03 07:21:51 +0000516 // In ObjC method declaration we align on the ":" of parameters, but we need
517 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasper37911302013-04-02 14:33:13 +0000518 if (Current.Type == TT_ObjCMethodSpecifier)
519 State.Stack.back().Indent += 4;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000520
Daniel Jasper29f123b2013-02-08 15:28:42 +0000521 // Insert scopes created by fake parenthesis.
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000522 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
523 // Don't add extra indentation for the first fake parenthesis after
524 // 'return', assignements or opening <({[. The indentation for these cases
525 // is special cased.
526 bool SkipFirstExtraIndent =
527 Current.is(tok::kw_return) ||
Daniel Jasperac3223e2013-04-10 09:49:49 +0000528 (Previous && (Previous->opensScope() ||
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000529 getPrecedence(*Previous) == prec::Assignment));
530 for (SmallVector<prec::Level, 4>::const_reverse_iterator
531 I = Current.FakeLParens.rbegin(),
532 E = Current.FakeLParens.rend();
533 I != E; ++I) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000534 ParenState NewParenState = State.Stack.back();
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000535 NewParenState.Indent =
536 std::max(std::max(State.Column, NewParenState.Indent),
537 State.Stack.back().LastSpace);
538
539 // Always indent conditional expressions. Never indent expression where
540 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
541 // prec::Assignment) as those have different indentation rules. Indent
542 // other expression, unless the indentation needs to be skipped.
543 if (*I == prec::Conditional ||
544 (!SkipFirstExtraIndent && *I > prec::Assignment))
545 NewParenState.Indent += 4;
Daniel Jasperac3223e2013-04-10 09:49:49 +0000546 if (Previous && !Previous->opensScope())
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000547 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000548 State.Stack.push_back(NewParenState);
Daniel Jasperbf71ba22013-04-08 20:33:42 +0000549 SkipFirstExtraIndent = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000550 }
551
Daniel Jaspercf225b62012-12-24 13:43:52 +0000552 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000553 // prepare for the following tokens.
Daniel Jasperac3223e2013-04-10 09:49:49 +0000554 if (Current.opensScope()) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000555 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000556 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000557 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000558 NewIndent = 2 + State.Stack.back().LastSpace;
559 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000560 } else {
Daniel Jasper24849712013-03-01 16:48:32 +0000561 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
562 State.Stack.back().StartOfFunctionCall);
Daniel Jasper3a39ac72013-02-28 09:39:12 +0000563 AvoidBinPacking =
564 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000565 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000566 State.Stack.push_back(
567 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
568 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000569 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000570 }
571
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000572 // If this '[' opens an ObjC call, determine whether all parameters fit into
573 // one line and put one per line if they don't.
574 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
575 Current.MatchingParen != NULL) {
576 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
577 State.Stack.back().BreakBeforeParameter = true;
578 }
579
Daniel Jaspercf225b62012-12-24 13:43:52 +0000580 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000581 // stacks.
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000582 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000583 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
584 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000585 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000586 --State.ParenLevel;
587 }
588
589 // Remove scopes created by fake parenthesis.
590 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000591 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000592 State.Stack.pop_back();
Daniel Jasperabfc9c12013-04-04 19:31:00 +0000593 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000594 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000595
Manuel Klimeke9a62262013-02-20 15:32:58 +0000596 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000597 State.StartOfStringLiteral = State.Column;
598 } else if (Current.isNot(tok::comment)) {
599 State.StartOfStringLiteral = 0;
600 }
601
Manuel Klimek8092a942013-02-20 10:15:13 +0000602 State.Column += Current.FormatTok.TokenLength;
603
Daniel Jasper26f7e782013-01-08 14:56:18 +0000604 if (State.NextToken->Children.empty())
605 State.NextToken = NULL;
606 else
607 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000608
Manuel Klimek8092a942013-02-20 10:15:13 +0000609 return breakProtrudingToken(Current, State, DryRun);
610 }
611
612 /// \brief If the current token sticks out over the end of the line, break
613 /// it if possible.
614 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
615 bool DryRun) {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000616 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek8092a942013-02-20 10:15:13 +0000617 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000618 if (Current.is(tok::string_literal)) {
619 // Only break up default narrow strings.
620 const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
621 if (!LiteralData || *LiteralData != '"')
622 return 0;
623
624 Token.reset(new BreakableStringLiteral(Current.FormatTok, StartColumn));
625 } else if (Current.Type == TT_BlockComment) {
626 BreakableBlockComment *BBC =
627 new BreakableBlockComment(SourceMgr, Current, StartColumn);
628 if (!DryRun)
629 BBC->alignLines(Whitespaces);
630 Token.reset(BBC);
631 } else {
632 return 0;
633 }
634
635 if (Token->getPrefixLength() + Token->getSuffixLength(0) >
636 getColumnLimit()) {
637 return 0;
638 }
639
640 bool BreakInserted = false;
641 unsigned Penalty = 0;
642 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
643 ++LineIndex) {
644 unsigned TokenLineSize = Token->getLineSize(LineIndex);
645 unsigned TailOffset = 0;
646 unsigned RemainingLength =
647 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
648 while (RemainingLength > getColumnLimit()) {
649 unsigned DecorationLength =
650 RemainingLength - (TokenLineSize - TailOffset);
651 if (DecorationLength + 1 > getColumnLimit()) {
652 // Can't reduce line length by splitting here.
653 break;
654 }
655 BreakableToken::Split Split =
656 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
657 if (Split.first == StringRef::npos)
658 break;
659 assert(Split.first != 0);
660 if (!DryRun) {
661 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
662 Whitespaces);
663 }
664 TailOffset += Split.first + Split.second;
Alexander Kornienkoe2657dd2013-04-15 15:47:34 +0000665 unsigned NewRemainingLength =
666 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
667 assert(NewRemainingLength < RemainingLength);
668 RemainingLength = NewRemainingLength;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000669 Penalty += Style.PenaltyExcessCharacter;
670 BreakInserted = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000671 }
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000672 State.Column = RemainingLength;
673 if (!DryRun) {
674 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
675 }
676 }
677
678 if (BreakInserted) {
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000679 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
680 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000681 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek8092a942013-02-20 10:15:13 +0000682 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000683 return Penalty;
684 }
685
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000686 unsigned getColumnLimit() {
Alexander Kornienko70ce7882013-04-15 14:28:00 +0000687 // In preprocessor directives reserve two chars for trailing " \"
688 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000689 }
690
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000691 /// \brief An edge in the solution space from \c Previous->State to \c State,
692 /// inserting a newline dependent on the \c NewLine.
693 struct StateNode {
694 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000695 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000696 LineState State;
697 bool NewLine;
698 StateNode *Previous;
699 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000700
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000701 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
702 ///
703 /// In case of equal penalties, we want to prefer states that were inserted
704 /// first. During state generation we make sure that we insert states first
705 /// that break the line as late as possible.
706 typedef std::pair<unsigned, unsigned> OrderedPenalty;
707
708 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
709 /// \c State has the given \c OrderedPenalty.
710 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
711
712 /// \brief The BFS queue type.
713 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
714 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000715
716 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000717 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000718 /// This implements a variant of Dijkstra's algorithm on the graph that spans
719 /// the solution space (\c LineStates are the nodes). The algorithm tries to
720 /// find the shortest path (the one with lowest penalty) from \p InitialState
721 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000722 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000723 std::set<LineState> Seen;
724
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000725 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000726 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000727 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
728 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
729 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000730
731 // While not empty, take first element and follow edges.
732 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000733 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000734 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000735 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000736 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000737 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000738 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000739 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000740
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000741 if (!Seen.insert(Node->State).second)
742 // State already examined with lower penalty.
743 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000744
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000745 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
746 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000747 }
748
749 if (Queue.empty())
750 // We were unable to find a solution, do nothing.
751 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000752 return 0;
753
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000754 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000755 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000756 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000757
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000758 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000759 return Queue.top().second->State.Column;
760 }
761
762 void reconstructPath(LineState &State, StateNode *Current) {
763 // FIXME: This recursive implementation limits the possible number
764 // of tokens per line if compiled into a binary with small stack space.
765 // To become more independent of stack frame limitations we would need
766 // to also change the TokenAnnotator.
767 if (Current->Previous == NULL)
768 return;
769 reconstructPath(State, Current->Previous);
770 DEBUG({
771 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000772 llvm::errs()
773 << "Penalty for splitting before "
774 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
775 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000776 }
777 });
778 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000779 }
780
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000781 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000782 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000783 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000784 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000785 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
786 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000787 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000788 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000789 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000790 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000791 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000792 Penalty += PreviousNode->State.NextToken->SplitPenalty;
793
794 StateNode *Node = new (Allocator.Allocate())
795 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000796 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000797 if (Node->State.Column > getColumnLimit()) {
798 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000799 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000800 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000801
802 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
803 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000804 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000805
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000806 /// \brief Returns \c true, if a line break after \p State is allowed.
807 bool canBreak(const LineState &State) {
808 if (!State.NextToken->CanBreakBefore &&
809 !(State.NextToken->is(tok::r_brace) &&
810 State.Stack.back().BreakBeforeClosingBrace))
811 return false;
812 // Trying to insert a parameter on a new line if there are already more than
813 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000814 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000815 State.Stack.back().AvoidBinPacking)
816 return false;
817 return true;
818 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000819
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000820 /// \brief Returns \c true, if a line break after \p State is mandatory.
821 bool mustBreak(const LineState &State) {
822 if (State.NextToken->MustBreakBefore)
823 return true;
824 if (State.NextToken->is(tok::r_brace) &&
825 State.Stack.back().BreakBeforeClosingBrace)
826 return true;
827 if (State.NextToken->Parent->is(tok::semi) &&
828 State.LineContainsContinuedForLoopSection)
829 return true;
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000830 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000831 State.NextToken->is(tok::question) ||
832 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000833 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperac3223e2013-04-10 09:49:49 +0000834 !State.NextToken->isTrailingComment() &&
Daniel Jasper7d812812013-02-21 15:00:29 +0000835 State.NextToken->isNot(tok::r_paren) &&
836 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000837 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000838 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
839 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000840 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000841 State.NextToken->LongestObjCSelectorName == 0 &&
842 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000843 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000844 if ((State.NextToken->Type == TT_CtorInitializerColon ||
845 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000846 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000847 return true;
Daniel Jasper923ebef2013-03-14 13:45:21 +0000848 if (State.NextToken->Type == TT_InlineASMColon)
849 return true;
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000850 // This prevents breaks like:
851 // ...
852 // SomeParameter, OtherParameter).DoSomething(
853 // ...
854 // As they hide "DoSomething" and generally bad for readability.
855 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
856 getRemainingLength(State) + State.Column > getColumnLimit() &&
857 State.ParenLevel < State.StartOfLineLevel)
858 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000859 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000860 }
861
Daniel Jasper3af59ce2013-03-15 14:57:30 +0000862 // Returns the total number of columns required for the remaining tokens.
863 unsigned getRemainingLength(const LineState &State) {
864 if (State.NextToken && State.NextToken->Parent)
865 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
866 return 0;
867 }
868
Daniel Jasperbac016b2012-12-03 18:12:45 +0000869 FormatStyle Style;
870 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000871 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000872 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000873 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000874 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000875
876 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
877 QueueType Queue;
878 // Increasing count of \c StateNode items we have created. This is used
879 // to create a deterministic order independent of the container.
880 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000881};
882
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000883class LexerBasedFormatTokenSource : public FormatTokenSource {
884public:
885 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000886 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000887 IdentTable(Lex.getLangOpts()) {
888 Lex.SetKeepWhitespaceMode(true);
889 }
890
891 virtual FormatToken getNextToken() {
892 if (GreaterStashed) {
893 FormatTok.NewlinesBefore = 0;
894 FormatTok.WhiteSpaceStart =
895 FormatTok.Tok.getLocation().getLocWithOffset(1);
896 FormatTok.WhiteSpaceLength = 0;
897 GreaterStashed = false;
898 return FormatTok;
899 }
900
901 FormatTok = FormatToken();
902 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000903 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000904 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000905 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
906 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000907
908 // Consume and record whitespace until we find a significant token.
909 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000910 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +0000911 if (Newlines > 0)
912 FormatTok.LastNewlineOffset =
913 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +0000914 unsigned EscapedNewlines = Text.count("\\\n");
915 FormatTok.NewlinesBefore += Newlines;
916 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000917 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
918
919 if (FormatTok.Tok.is(tok::eof))
920 return FormatTok;
921 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000922 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000923 }
Manuel Klimek95419382013-01-07 07:56:50 +0000924
925 // Now FormatTok is the next non-whitespace token.
926 FormatTok.TokenLength = Text.size();
927
Manuel Klimekd4397b92013-01-04 23:34:14 +0000928 // In case the token starts with escaped newlines, we want to
929 // take them into account as whitespace - this pattern is quite frequent
930 // in macro definitions.
931 // FIXME: What do we want to do with other escaped spaces, and escaped
932 // spaces or newlines in the middle of tokens?
933 // FIXME: Add a more explicit test.
934 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000935 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000936 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000937 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000938 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000939 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000940 }
941
942 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000943 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000944 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000945 FormatTok.Tok.setKind(Info.getTokenID());
946 }
947
948 if (FormatTok.Tok.is(tok::greatergreater)) {
949 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +0000950 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000951 GreaterStashed = true;
952 }
953
Daniel Jasper812c0452013-03-01 16:45:59 +0000954 // If we reformat comments, we remove trailing whitespace. Update the length
955 // accordingly.
956 if (FormatTok.Tok.is(tok::comment))
957 FormatTok.TokenLength = Text.rtrim().size();
958
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000959 return FormatTok;
960 }
961
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000962 IdentifierTable &getIdentTable() { return IdentTable; }
963
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000964private:
965 FormatToken FormatTok;
966 bool GreaterStashed;
967 Lexer &Lex;
968 SourceManager &SourceMgr;
969 IdentifierTable IdentTable;
970
971 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000972 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000973 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
974 Tok.getLength());
975 }
976};
977
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978class Formatter : public UnwrappedLineConsumer {
979public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000980 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
981 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000982 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000983 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko052685c2013-03-19 17:41:36 +0000984 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000985
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000986 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000987
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000988 tooling::Replacements format() {
989 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
990 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek67d080d2013-04-12 14:13:36 +0000991 bool StructuralError = Parser.parse();
Alexander Kornienkoe74de282013-03-13 14:41:29 +0000992 unsigned PreviousEndOfLineColumn = 0;
993 TokenAnnotator Annotator(Style, SourceMgr, Lex,
994 Tokens.getIdentTable().get("in"));
995 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
996 Annotator.annotate(AnnotatedLines[i]);
997 }
998 deriveLocalStyle();
999 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1000 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
1001 }
Daniel Jasper5999f762013-04-09 17:46:55 +00001002
1003 // Adapt level to the next line if this is a comment.
1004 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper1407bee2013-04-11 14:29:13 +00001005 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001006 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
1007 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
1008 AnnotatedLines[i].First.Children.empty())
1009 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
1010 else
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001011 NextNoneCommentLine =
1012 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1013 : NULL;
Daniel Jasper5999f762013-04-09 17:46:55 +00001014 }
1015
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001016 std::vector<int> IndentForLevel;
1017 bool PreviousLineWasTouched = false;
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001018 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001019 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1020 E = AnnotatedLines.end();
1021 I != E; ++I) {
1022 const AnnotatedLine &TheLine = *I;
1023 const FormatToken &FirstTok = TheLine.First.FormatTok;
1024 int Offset = getIndentOffset(TheLine.First);
1025 while (IndentForLevel.size() <= TheLine.Level)
1026 IndentForLevel.push_back(-1);
1027 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperf9955d32013-03-20 12:37:50 +00001028 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001029 if (TheLine.First.is(tok::eof)) {
1030 if (PreviousLineWasTouched) {
1031 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1032 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001033 /*WhitespaceStartColumn*/ 0);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001034 }
1035 } else if (TheLine.Type != LT_Invalid &&
1036 (WasMoved || touchesLine(TheLine))) {
1037 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1038 unsigned Indent = LevelIndent;
1039 if (static_cast<int>(Indent) + Offset >= 0)
1040 Indent += Offset;
Manuel Klimek67d080d2013-04-12 14:13:36 +00001041 if (FirstTok.WhiteSpaceStart.isValid() &&
1042 // Insert a break even if there is a structural error in case where
1043 // we break apart a line consisting of multiple unwrapped lines.
1044 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001045 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1046 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek67d080d2013-04-12 14:13:36 +00001047 } else {
1048 Indent = LevelIndent =
1049 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001050 }
1051 tryFitMultipleLinesInOne(Indent, I, E);
1052 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek67d080d2013-04-12 14:13:36 +00001053 TheLine.First, Whitespaces);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001054 PreviousEndOfLineColumn =
1055 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1056 IndentForLevel[TheLine.Level] = LevelIndent;
1057 PreviousLineWasTouched = true;
1058 } else {
1059 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1060 unsigned Indent =
1061 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1062 unsigned LevelIndent = Indent;
1063 if (static_cast<int>(LevelIndent) - Offset >= 0)
1064 LevelIndent -= Offset;
Daniel Jasper83a90e52013-03-20 14:31:47 +00001065 if (TheLine.First.isNot(tok::comment))
1066 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001067
1068 // Remove trailing whitespace of the previous line if it was touched.
1069 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001070 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1071 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001072 }
1073 // If we did not reformat this unwrapped line, the column at the end of
1074 // the last token is unchanged - thus, we can calculate the end of the
1075 // last token.
1076 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1077 PreviousEndOfLineColumn =
1078 SourceMgr.getSpellingColumnNumber(LastLoc) +
1079 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1080 PreviousLineWasTouched = false;
Daniel Jasperc363dbb2013-03-22 16:25:51 +00001081 if (TheLine.Last->is(tok::comment))
1082 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1083 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001084 }
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001085 PreviousLineLastToken = I->Last;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001086 }
1087 return Whitespaces.generateReplacements();
1088 }
1089
1090private:
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001091 void deriveLocalStyle() {
1092 unsigned CountBoundToVariable = 0;
1093 unsigned CountBoundToType = 0;
1094 bool HasCpp03IncompatibleFormat = false;
1095 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1096 if (AnnotatedLines[i].First.Children.empty())
1097 continue;
1098 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1099 while (!Tok->Children.empty()) {
1100 if (Tok->Type == TT_PointerOrReference) {
1101 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1102 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1103 if (SpacesBefore && !SpacesAfter)
1104 ++CountBoundToVariable;
1105 else if (!SpacesBefore && SpacesAfter)
1106 ++CountBoundToType;
1107 }
1108
Daniel Jasper29f123b2013-02-08 15:28:42 +00001109 if (Tok->Type == TT_TemplateCloser &&
1110 Tok->Parent->Type == TT_TemplateCloser &&
1111 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001112 HasCpp03IncompatibleFormat = true;
1113 Tok = &Tok->Children[0];
1114 }
1115 }
1116 if (Style.DerivePointerBinding) {
1117 if (CountBoundToType > CountBoundToVariable)
1118 Style.PointerBindsToType = true;
1119 else if (CountBoundToType < CountBoundToVariable)
1120 Style.PointerBindsToType = false;
1121 }
1122 if (Style.Standard == FormatStyle::LS_Auto) {
1123 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1124 : FormatStyle::LS_Cpp03;
1125 }
1126 }
1127
Manuel Klimek547d5db2013-02-08 17:38:27 +00001128 /// \brief Get the indent of \p Level from \p IndentForLevel.
1129 ///
1130 /// \p IndentForLevel must contain the indent for the level \c l
1131 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1132 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001133 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001134 if (IndentForLevel[Level] != -1)
1135 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001136 if (Level == 0)
1137 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001138 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001139 }
1140
1141 /// \brief Get the offset of the line relatively to the level.
1142 ///
1143 /// For example, 'public:' labels in classes are offset by 1 or 2
1144 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001145 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001146 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimek547d5db2013-02-08 17:38:27 +00001147 return Style.AccessModifierOffset;
1148 return 0;
1149 }
1150
Manuel Klimek517e8942013-01-11 17:54:10 +00001151 /// \brief Tries to merge lines into one.
1152 ///
1153 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1154 /// if possible; note that \c I will be incremented when lines are merged.
1155 ///
1156 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001157 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001158 std::vector<AnnotatedLine>::iterator &I,
1159 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001160 // We can never merge stuff if there are trailing line comments.
1161 if (I->Last->Type == TT_LineComment)
1162 return;
1163
Daniel Jaspera4d46212013-02-28 11:05:57 +00001164 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001165 // If we already exceed the column limit, we set 'Limit' to 0. The different
1166 // tryMerge..() functions can then decide whether to still do merging.
1167 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001168
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001169 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001170 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001171
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001172 if (I->Last->is(tok::l_brace)) {
1173 tryMergeSimpleBlock(I, E, Limit);
1174 } else if (I->First.is(tok::kw_if)) {
1175 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001176 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1177 I->First.FormatTok.IsFirst)) {
1178 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001179 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001180 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001181 }
1182
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001183 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1184 std::vector<AnnotatedLine>::iterator E,
1185 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001186 if (Limit == 0)
1187 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001188 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001189 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1190 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001191 if (I + 2 != E && (I + 2)->InPPDirective &&
1192 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1193 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001194 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001195 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001196 join(Line, *(++I));
1197 }
1198
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001199 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1200 std::vector<AnnotatedLine>::iterator E,
1201 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001202 if (Limit == 0)
1203 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001204 if (!Style.AllowShortIfStatementsOnASingleLine)
1205 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001206 if ((I + 1)->InPPDirective != I->InPPDirective ||
1207 ((I + 1)->InPPDirective &&
1208 (I + 1)->First.FormatTok.HasUnescapedNewline))
1209 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001210 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001211 if (Line.Last->isNot(tok::r_paren))
1212 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001213 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001214 return;
1215 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1216 return;
1217 // Only inline simple if's (no nested if or else).
1218 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1219 return;
1220 join(Line, *(++I));
1221 }
1222
1223 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001224 std::vector<AnnotatedLine>::iterator E,
1225 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001226 // First, check that the current line allows merging. This is the case if
1227 // we're not in a control flow statement and the last token is an opening
1228 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001229 AnnotatedLine &Line = *I;
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001230 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1231 tok::kw_else, tok::kw_try, tok::kw_catch,
1232 tok::kw_for,
1233 // This gets rid of all ObjC @ keywords and methods.
1234 tok::at, tok::minus, tok::plus))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001235 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001236
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001237 AnnotatedToken *Tok = &(I + 1)->First;
1238 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001239 !Tok->MustBreakBefore) {
1240 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001241 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001242 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001243 join(Line, *(I + 1));
1244 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001245 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001246 // Check that we still have three lines and they fit into the limit.
1247 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1248 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001249 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001250
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001251 // Second, check that the next line does not contain any braces - if it
1252 // does, readability declines when putting it into a single line.
1253 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1254 return;
1255 do {
Alexander Kornienkoe74de282013-03-13 14:41:29 +00001256 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001257 return;
1258 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1259 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001260
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001261 // Last, check that the third line contains a single closing brace.
1262 Tok = &(I + 2)->First;
1263 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1264 Tok->MustBreakBefore)
1265 return;
1266
1267 join(Line, *(I + 1));
1268 join(Line, *(I + 2));
1269 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001270 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001271 }
1272
1273 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1274 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001275 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1276 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001277 }
1278
Daniel Jasper995e8202013-01-14 13:08:07 +00001279 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001280 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001281 A.Last->Children.push_back(B.First);
1282 while (!A.Last->Children.empty()) {
1283 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001284 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001285 A.Last = &A.Last->Children[0];
1286 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001287 }
1288
Daniel Jasper6f21a982013-03-13 07:49:51 +00001289 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf3023542013-03-07 20:50:00 +00001290 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1291 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1292 Ranges[i].getBegin()) &&
1293 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1294 Range.getBegin()))
1295 return true;
1296 }
1297 return false;
1298 }
1299
1300 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001301 const FormatToken *First = &TheLine.First.FormatTok;
1302 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001303 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001304 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1305 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001306 return touchesRanges(LineRange);
1307 }
1308
1309 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1310 const FormatToken *First = &TheLine.First.FormatTok;
1311 CharSourceRange LineRange = CharSourceRange::getCharRange(
1312 First->WhiteSpaceStart,
1313 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1314 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001315 }
1316
1317 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001318 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001319 }
1320
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001321 /// \brief Add a new line and the required indent before the first Token
1322 /// of the \c UnwrappedLine if there was no structural parsing error.
1323 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001324 void formatFirstToken(const AnnotatedToken &RootToken,
1325 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimek547d5db2013-02-08 17:38:27 +00001326 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001327 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001328
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001329 unsigned Newlines =
1330 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001331 if (Newlines == 0 && !Tok.IsFirst)
1332 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001333
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001334 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienko94b748f2013-03-27 17:08:02 +00001335 // Insert extra new line before access specifiers.
1336 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1337 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1338 ++Newlines;
1339
Alexander Kornienko052685c2013-03-19 17:41:36 +00001340 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001341 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001342 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienko052685c2013-03-19 17:41:36 +00001343 PreviousEndOfLineColumn);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001344 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001345 }
1346
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001347 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001348 FormatStyle Style;
1349 Lexer &Lex;
1350 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001351 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001352 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001353 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001354};
1355
Alexander Kornienko70ce7882013-04-15 14:28:00 +00001356tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1357 SourceManager &SourceMgr,
1358 std::vector<CharSourceRange> Ranges,
1359 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001360 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001361 OwningPtr<DiagnosticConsumer> DiagPrinter;
1362 if (DiagClient == 0) {
1363 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1364 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1365 DiagClient = DiagPrinter.get();
1366 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001367 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001368 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001369 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001370 Diagnostics.setSourceManager(&SourceMgr);
1371 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001372 return formatter.format();
1373}
1374
Daniel Jasper46ef8522013-01-10 13:08:12 +00001375LangOptions getFormattingLangOpts() {
1376 LangOptions LangOpts;
1377 LangOpts.CPlusPlus = 1;
1378 LangOpts.CPlusPlus11 = 1;
Daniel Jasperb64eca02013-03-22 10:01:29 +00001379 LangOpts.LineComment = 1;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001380 LangOpts.Bool = 1;
1381 LangOpts.ObjC1 = 1;
1382 LangOpts.ObjC2 = 1;
1383 return LangOpts;
1384}
1385
Daniel Jaspercd162382013-01-07 13:26:07 +00001386} // namespace format
1387} // namespace clang