blob: 2538f33f5070dce16a12ebb2375de4c97985641f [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 Jaspercc960fa2013-04-22 07:59:53 +0000119 /*NoLineBreak=*/ 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,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000159 bool NoLineBreak)
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 Jaspercc960fa2013-04-22 07:59:53 +0000163 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
164 NestedNameSpecifierContinuation(0), CallContinuation(0),
165 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
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000202 /// \brief Line breaking in this context would break a formatting rule.
203 bool NoLineBreak;
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 Jaspercc960fa2013-04-22 07:59:53 +0000239 if (NoLineBreak != Other.NoLineBreak)
240 return NoLineBreak;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000241 if (ColonPos != Other.ColonPos)
242 return ColonPos < Other.ColonPos;
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000243 if (StartOfFunctionCall != Other.StartOfFunctionCall)
244 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperc238c872013-04-02 14:33:13 +0000245 if (NestedNameSpecifierContinuation !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000246 Other.NestedNameSpecifierContinuation)
Daniel Jasperc238c872013-04-02 14:33:13 +0000247 return NestedNameSpecifierContinuation <
248 Other.NestedNameSpecifierContinuation;
249 if (CallContinuation != Other.CallContinuation)
250 return CallContinuation < Other.CallContinuation;
Daniel Jaspera628c982013-04-03 13:36:17 +0000251 if (VariablePos != Other.VariablePos)
252 return VariablePos < Other.VariablePos;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000253 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000254 }
255 };
256
257 /// \brief The current state when indenting a unwrapped line.
258 ///
259 /// As the indenting tries different combinations this is copied by value.
260 struct LineState {
261 /// \brief The number of used columns in the current line.
262 unsigned Column;
263
264 /// \brief The token that needs to be next formatted.
265 const AnnotatedToken *NextToken;
266
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000267 /// \brief \c true if this line contains a continued for-loop section.
268 bool LineContainsContinuedForLoopSection;
269
Daniel Jasper400adc62013-02-08 15:28:42 +0000270 /// \brief The level of nesting inside (), [], <> and {}.
271 unsigned ParenLevel;
272
Daniel Jasper40c36c52013-02-18 11:05:07 +0000273 /// \brief The \c ParenLevel at the start of this line.
274 unsigned StartOfLineLevel;
275
Manuel Klimek02f640a2013-02-20 15:25:48 +0000276 /// \brief The start column of the string literal, if we're in a string
277 /// literal sequence, 0 otherwise.
278 unsigned StartOfStringLiteral;
279
Daniel Jasper337816e2013-01-11 10:22:12 +0000280 /// \brief A stack keeping track of properties applying to parenthesis
281 /// levels.
282 std::vector<ParenState> Stack;
283
284 /// \brief Comparison operator to be able to used \c LineState in \c map.
285 bool operator<(const LineState &Other) const {
Daniel Jasper58f427e2013-02-19 09:28:55 +0000286 if (NextToken != Other.NextToken)
287 return NextToken < Other.NextToken;
288 if (Column != Other.Column)
289 return Column < Other.Column;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000290 if (LineContainsContinuedForLoopSection !=
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000291 Other.LineContainsContinuedForLoopSection)
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000292 return LineContainsContinuedForLoopSection;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000293 if (ParenLevel != Other.ParenLevel)
294 return ParenLevel < Other.ParenLevel;
295 if (StartOfLineLevel != Other.StartOfLineLevel)
296 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimek02f640a2013-02-20 15:25:48 +0000297 if (StartOfStringLiteral != Other.StartOfStringLiteral)
298 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasper58f427e2013-02-19 09:28:55 +0000299 return Stack < Other.Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000300 }
301 };
302
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000303 /// \brief Appends the next token to \p State and updates information
304 /// necessary for indentation.
305 ///
306 /// Puts the token on the current line if \p Newline is \c true and adds a
307 /// line break and necessary indentation otherwise.
308 ///
309 /// If \p DryRun is \c false, also creates and stores the required
310 /// \c Replacement.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000311 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000312 const AnnotatedToken &Current = *State.NextToken;
313 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000314
Daniel Jasper291f9362013-03-20 15:58:10 +0000315 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
Daniel Jasper4b866272013-02-01 11:00:45 +0000316 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
317 State.NextToken->FormatTok.TokenLength;
318 if (State.NextToken->Children.empty())
319 State.NextToken = NULL;
320 else
321 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek1998ea22013-02-20 10:15:13 +0000322 return 0;
Daniel Jasper4b866272013-02-01 11:00:45 +0000323 }
324
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000325 // If we are continuing an expression, we want to indent an extra 4 spaces.
326 unsigned ContinuationIndent =
Daniel Jasperc238c872013-04-02 14:33:13 +0000327 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000329 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000330 if (Current.is(tok::r_brace)) {
331 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000332 } else if (Current.is(tok::string_literal) &&
Manuel Klimek02f640a2013-02-20 15:25:48 +0000333 State.StartOfStringLiteral != 0) {
334 State.Column = State.StartOfStringLiteral;
Daniel Jasper2ec3ffb82013-02-18 11:59:17 +0000335 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000336 } else if (Current.is(tok::lessless) &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000337 State.Stack.back().FirstLessLess != 0) {
338 State.Column = State.Stack.back().FirstLessLess;
Daniel Jasperc238c872013-04-02 14:33:13 +0000339 } else if (Previous.is(tok::coloncolon)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000340 if (State.Stack.back().NestedNameSpecifierContinuation == 0) {
341 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000342 State.Stack.back().NestedNameSpecifierContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000343 } else {
344 State.Column = State.Stack.back().NestedNameSpecifierContinuation;
345 }
Daniel Jasperc238c872013-04-02 14:33:13 +0000346 } else if (Current.isOneOf(tok::period, tok::arrow)) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000347 if (State.Stack.back().CallContinuation == 0) {
348 State.Column = ContinuationIndent;
Daniel Jasperc238c872013-04-02 14:33:13 +0000349 State.Stack.back().CallContinuation = State.Column;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000350 } else {
351 State.Column = State.Stack.back().CallContinuation;
352 }
Daniel Jasperca6623b2013-01-28 12:45:14 +0000353 } else if (Current.Type == TT_ConditionalExpr) {
354 State.Column = State.Stack.back().QuestionColumn;
Daniel Jaspera628c982013-04-03 13:36:17 +0000355 } else if (Previous.is(tok::comma) &&
356 State.Stack.back().VariablePos != 0) {
357 State.Column = State.Stack.back().VariablePos;
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000358 } else if (Previous.ClosesTemplateDeclaration ||
359 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasperc238c872013-04-02 14:33:13 +0000360 State.Column = State.Stack.back().Indent;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000361 } else if (Current.Type == TT_ObjCSelectorName) {
362 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
363 State.Column =
364 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
365 } else {
366 State.Column = State.Stack.back().Indent;
367 State.Stack.back().ColonPos =
368 State.Column + Current.FormatTok.TokenLength;
369 }
Daniel Jasper6bee6822013-04-08 20:33:42 +0000370 } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Daniel Jasperc238c872013-04-02 14:33:13 +0000371 Previous.Type == TT_ObjCMethodExpr) {
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000372 State.Column = ContinuationIndent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000373 } else {
Daniel Jasper400adc62013-02-08 15:28:42 +0000374 State.Column = State.Stack.back().Indent;
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000375 // Ensure that we fall back to indenting 4 spaces instead of just
376 // flushing continuations left.
Daniel Jasperc238c872013-04-02 14:33:13 +0000377 if (State.Column == FirstIndent)
378 State.Column += 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000379 }
380
Daniel Jasper54a86022013-02-15 11:07:25 +0000381 if (Current.is(tok::question))
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000382 State.Stack.back().BreakBeforeParameter = true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000383 if (Previous.isOneOf(tok::comma, tok::semi) &&
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000384 !State.Stack.back().AvoidBinPacking)
Daniel Jasperacc33662013-02-08 08:22:00 +0000385 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000386
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000387 if (!DryRun) {
Daniel Jasperfb5e2412013-02-26 13:10:34 +0000388 unsigned NewLines = 1;
389 if (Current.Type == TT_LineComment)
390 NewLines =
391 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
392 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000393 if (!Line.InPPDirective)
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000394 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000395 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000396 else
Daniel Jasperdc7d5812013-02-20 12:56:39 +0000397 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000398 WhitespaceStartColumn);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000399 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000400
Daniel Jasper400adc62013-02-08 15:28:42 +0000401 State.Stack.back().LastSpace = State.Column;
Daniel Jasper40c36c52013-02-18 11:05:07 +0000402 State.StartOfLineLevel = State.ParenLevel;
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000403
404 // Any break on this level means that the parent level has been broken
405 // and we need to avoid bin packing there.
406 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
407 State.Stack[i].BreakBeforeParameter = true;
408 }
Daniel Jasper1b8e76f2013-04-15 22:36:37 +0000409 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
410 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
411 !TokenBefore->opensScope())
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000412 State.Stack.back().BreakBeforeParameter = true;
413
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000414 // If we break after {, we should also break before the corresponding }.
415 if (Previous.is(tok::l_brace))
416 State.Stack.back().BreakBeforeClosingBrace = true;
417
418 if (State.Stack.back().AvoidBinPacking) {
419 // If we are breaking after '(', '{', '<', this is not bin packing
420 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper26d1b1d2013-02-24 18:54:32 +0000421 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000422 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
423 Line.MustBeDeclaration))
424 State.Stack.back().BreakBeforeParameter = true;
425 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 } else {
Daniel Jasper62e68172013-02-25 15:59:54 +0000427 if (Current.is(tok::equal) &&
Daniel Jasper31c96b92013-04-05 09:38:50 +0000428 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) &&
429 State.Stack.back().VariablePos == 0) {
430 State.Stack.back().VariablePos = State.Column;
431 // Move over * and & if they are bound to the variable name.
432 const AnnotatedToken *Tok = &Previous;
433 while (Tok &&
434 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) {
435 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength;
436 if (Tok->SpacesRequiredBefore != 0)
437 break;
438 Tok = Tok->Parent;
439 }
Daniel Jaspera628c982013-04-03 13:36:17 +0000440 if (Previous.PartOfMultiVariableDeclStmt)
441 State.Stack.back().LastSpace = State.Stack.back().VariablePos;
442 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000443
Daniel Jaspereef30492013-02-11 12:36:37 +0000444 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000445
Daniel Jasperf7935112012-12-03 18:12:45 +0000446 if (!DryRun)
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000447 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000448
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000449 if (Current.Type == TT_ObjCSelectorName &&
450 State.Stack.back().ColonPos == 0) {
451 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000452 State.Column + Spaces + Current.FormatTok.TokenLength)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000453 State.Stack.back().ColonPos =
454 State.Stack.back().Indent + Current.LongestObjCSelectorName;
455 else
456 State.Stack.back().ColonPos =
Daniel Jasperc485b4e2013-02-06 16:00:26 +0000457 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000458 }
459
Daniel Jasperc04baae2013-04-10 09:49:49 +0000460 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
Daniel Jasper6bee6822013-04-08 20:33:42 +0000461 Current.Type != TT_LineComment)
Daniel Jasper400adc62013-02-08 15:28:42 +0000462 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000463 if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
464 State.Stack.back().AvoidBinPacking)
465 State.Stack.back().NoLineBreak = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000466
Daniel Jaspere9de2602012-12-06 09:56:08 +0000467 State.Column += Spaces;
Daniel Jaspera628c982013-04-03 13:36:17 +0000468 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
Daniel Jasper39e27382013-01-23 20:41:06 +0000469 // Treat the condition inside an if as if it was a second function
470 // parameter, i.e. let nested calls have an indent of 4.
471 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasperd1ae3582013-03-20 12:37:50 +0000472 else if (Previous.is(tok::comma))
Daniel Jasper39e27382013-01-23 20:41:06 +0000473 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000474 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000475 Previous.Type == TT_ConditionalExpr ||
476 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000477 getPrecedence(Previous) != prec::Assignment)
478 State.Stack.back().LastSpace = State.Column;
Daniel Jaspereead02b2013-02-14 08:42:54 +0000479 else if (Previous.Type == TT_InheritanceColon)
480 State.Stack.back().Indent = State.Column;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000481 else if (Previous.opensScope() && Previous.ParameterCount > 1)
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000482 // If this function has multiple parameters, indent nested calls from
483 // the start of the first parameter.
484 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000485 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000486
Manuel Klimek1998ea22013-02-20 10:15:13 +0000487 return moveStateToNextToken(State, DryRun);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000488 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000489
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000490 /// \brief Mark the next token as consumed in \p State and modify its stacks
491 /// accordingly.
Manuel Klimek1998ea22013-02-20 10:15:13 +0000492 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000493 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000494 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000495
Daniel Jaspereead02b2013-02-14 08:42:54 +0000496 if (Current.Type == TT_InheritanceColon)
497 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper337816e2013-01-11 10:22:12 +0000498 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
499 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000500 if (Current.is(tok::question))
501 State.Stack.back().QuestionColumn = State.Column;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000502 if (Current.isOneOf(tok::period, tok::arrow) &&
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000503 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
504 State.Stack.back().StartOfFunctionCall =
505 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper37905f72013-02-21 15:00:29 +0000506 if (Current.Type == TT_CtorInitializerColon) {
Daniel Jasper6bee6822013-04-08 20:33:42 +0000507 State.Stack.back().Indent = State.Column + 2;
Daniel Jasper37905f72013-02-21 15:00:29 +0000508 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
509 State.Stack.back().AvoidBinPacking = true;
510 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000511 }
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000512
Daniel Jasper6bee6822013-04-08 20:33:42 +0000513 // If return returns a binary expression, align after it.
514 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
515 State.Stack.back().LastSpace = State.Column + 7;
516
Daniel Jasper5188e6b2013-04-03 07:21:51 +0000517 // In ObjC method declaration we align on the ":" of parameters, but we need
518 // to ensure that we indent parameters on subsequent lines by at least 4.
Daniel Jasperc238c872013-04-02 14:33:13 +0000519 if (Current.Type == TT_ObjCMethodSpecifier)
520 State.Stack.back().Indent += 4;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000521
Daniel Jasper400adc62013-02-08 15:28:42 +0000522 // Insert scopes created by fake parenthesis.
Daniel Jasper6bee6822013-04-08 20:33:42 +0000523 const AnnotatedToken *Previous = Current.getPreviousNoneComment();
524 // Don't add extra indentation for the first fake parenthesis after
525 // 'return', assignements or opening <({[. The indentation for these cases
526 // is special cased.
527 bool SkipFirstExtraIndent =
528 Current.is(tok::kw_return) ||
Daniel Jasperc04baae2013-04-10 09:49:49 +0000529 (Previous && (Previous->opensScope() ||
Daniel Jasper6bee6822013-04-08 20:33:42 +0000530 getPrecedence(*Previous) == prec::Assignment));
531 for (SmallVector<prec::Level, 4>::const_reverse_iterator
532 I = Current.FakeLParens.rbegin(),
533 E = Current.FakeLParens.rend();
534 I != E; ++I) {
Daniel Jasper400adc62013-02-08 15:28:42 +0000535 ParenState NewParenState = State.Stack.back();
Daniel Jasper6bee6822013-04-08 20:33:42 +0000536 NewParenState.Indent =
537 std::max(std::max(State.Column, NewParenState.Indent),
538 State.Stack.back().LastSpace);
539
540 // Always indent conditional expressions. Never indent expression where
541 // the 'operator' is ',', ';' or an assignment (i.e. *I <=
542 // prec::Assignment) as those have different indentation rules. Indent
543 // other expression, unless the indentation needs to be skipped.
544 if (*I == prec::Conditional ||
545 (!SkipFirstExtraIndent && *I > prec::Assignment))
546 NewParenState.Indent += 4;
Daniel Jasperc04baae2013-04-10 09:49:49 +0000547 if (Previous && !Previous->opensScope())
Daniel Jasper6bee6822013-04-08 20:33:42 +0000548 NewParenState.BreakBeforeParameter = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000549 State.Stack.push_back(NewParenState);
Daniel Jasper6bee6822013-04-08 20:33:42 +0000550 SkipFirstExtraIndent = false;
Daniel Jasper400adc62013-02-08 15:28:42 +0000551 }
552
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000553 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554 // prepare for the following tokens.
Daniel Jasperc04baae2013-04-10 09:49:49 +0000555 if (Current.opensScope()) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 unsigned NewIndent;
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000557 bool AvoidBinPacking;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000558 if (Current.is(tok::l_brace)) {
Daniel Jasper8a8ce242013-01-31 14:59:26 +0000559 NewIndent = 2 + State.Stack.back().LastSpace;
560 AvoidBinPacking = false;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000561 } else {
Daniel Jasperf9a84b52013-03-01 16:48:32 +0000562 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
563 State.Stack.back().StartOfFunctionCall);
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000564 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000565 }
Daniel Jasperb9ebd5d2013-02-05 09:41:21 +0000566 State.Stack.push_back(
567 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000568 State.Stack.back().NoLineBreak));
Daniel Jasper400adc62013-02-08 15:28:42 +0000569 ++State.ParenLevel;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000570 }
571
Daniel Jasperacc33662013-02-08 08:22:00 +0000572 // If this '[' opens an ObjC call, determine whether all parameters fit into
573 // one line and put one per line if they don't.
574 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
575 Current.MatchingParen != NULL) {
576 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
577 State.Stack.back().BreakBeforeParameter = true;
578 }
579
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000580 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000581 // stacks.
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000582 if (Current.isOneOf(tok::r_paren, tok::r_square) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000583 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
584 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 State.Stack.pop_back();
Daniel Jasper400adc62013-02-08 15:28:42 +0000586 --State.ParenLevel;
587 }
588
589 // Remove scopes created by fake parenthesis.
590 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
Daniel Jasper6daabe32013-04-04 19:31:00 +0000591 unsigned VariablePos = State.Stack.back().VariablePos;
Daniel Jasper400adc62013-02-08 15:28:42 +0000592 State.Stack.pop_back();
Daniel Jasper6daabe32013-04-04 19:31:00 +0000593 State.Stack.back().VariablePos = VariablePos;
Daniel Jasperf7935112012-12-03 18:12:45 +0000594 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000595
Manuel Klimek0c915712013-02-20 15:32:58 +0000596 if (Current.is(tok::string_literal)) {
Manuel Klimek02f640a2013-02-20 15:25:48 +0000597 State.StartOfStringLiteral = State.Column;
598 } else if (Current.isNot(tok::comment)) {
599 State.StartOfStringLiteral = 0;
600 }
601
Manuel Klimek1998ea22013-02-20 10:15:13 +0000602 State.Column += Current.FormatTok.TokenLength;
603
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000604 if (State.NextToken->Children.empty())
605 State.NextToken = NULL;
606 else
607 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000608
Manuel Klimek1998ea22013-02-20 10:15:13 +0000609 return breakProtrudingToken(Current, State, DryRun);
610 }
611
612 /// \brief If the current token sticks out over the end of the line, break
613 /// it if possible.
614 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
615 bool DryRun) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000616 llvm::OwningPtr<BreakableToken> Token;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000617 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000618 if (Current.is(tok::string_literal)) {
619 // Only break up default narrow strings.
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000620 const char *LiteralData = SourceMgr.getCharacterData(
621 Current.FormatTok.getStartOfNonWhitespace());
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000622 if (!LiteralData || *LiteralData != '"')
623 return 0;
624
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000625 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
626 StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000627 } else if (Current.Type == TT_BlockComment) {
628 BreakableBlockComment *BBC =
629 new BreakableBlockComment(SourceMgr, Current, StartColumn);
630 if (!DryRun)
631 BBC->alignLines(Whitespaces);
632 Token.reset(BBC);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000633 } else if (Current.Type == TT_LineComment) {
634 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000635 } else {
636 return 0;
637 }
638
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000639 bool BreakInserted = false;
640 unsigned Penalty = 0;
641 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
642 ++LineIndex) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000643 unsigned TailOffset = 0;
644 unsigned RemainingLength =
645 Token->getLineLengthAfterSplit(LineIndex, TailOffset);
646 while (RemainingLength > getColumnLimit()) {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000647 BreakableToken::Split Split =
648 Token->getSplit(LineIndex, TailOffset, getColumnLimit());
649 if (Split.first == StringRef::npos)
650 break;
651 assert(Split.first != 0);
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000652 unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
653 LineIndex, TailOffset + Split.first + Split.second);
654 if (NewRemainingLength >= RemainingLength)
655 break;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000656 if (!DryRun) {
657 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
658 Whitespaces);
659 }
660 TailOffset += Split.first + Split.second;
Alexander Kornienkoc3c8aff2013-04-15 15:47:34 +0000661 RemainingLength = NewRemainingLength;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000662 Penalty += Style.PenaltyExcessCharacter;
663 BreakInserted = true;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000664 }
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000665 State.Column = RemainingLength;
666 if (!DryRun) {
667 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
668 }
669 }
670
671 if (BreakInserted) {
Daniel Jasper2cf17bf2013-02-27 09:47:53 +0000672 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
673 State.Stack[i].BreakBeforeParameter = true;
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000674 State.Stack.back().LastSpace = StartColumn;
Manuel Klimek1998ea22013-02-20 10:15:13 +0000675 }
Manuel Klimek1998ea22013-02-20 10:15:13 +0000676 return Penalty;
677 }
678
Daniel Jasper2df93312013-01-09 10:16:05 +0000679 unsigned getColumnLimit() {
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000680 // In preprocessor directives reserve two chars for trailing " \"
681 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasper2df93312013-01-09 10:16:05 +0000682 }
683
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000684 /// \brief An edge in the solution space from \c Previous->State to \c State,
685 /// inserting a newline dependent on the \c NewLine.
686 struct StateNode {
687 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasper12ef4e52013-02-21 21:33:55 +0000688 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000689 LineState State;
690 bool NewLine;
691 StateNode *Previous;
692 };
Daniel Jasper4b866272013-02-01 11:00:45 +0000693
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000694 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
695 ///
696 /// In case of equal penalties, we want to prefer states that were inserted
697 /// first. During state generation we make sure that we insert states first
698 /// that break the line as late as possible.
699 typedef std::pair<unsigned, unsigned> OrderedPenalty;
700
701 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
702 /// \c State has the given \c OrderedPenalty.
703 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
704
705 /// \brief The BFS queue type.
706 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
707 std::greater<QueueItem> > QueueType;
Daniel Jasper4b866272013-02-01 11:00:45 +0000708
709 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 ///
Daniel Jasper4b866272013-02-01 11:00:45 +0000711 /// This implements a variant of Dijkstra's algorithm on the graph that spans
712 /// the solution space (\c LineStates are the nodes). The algorithm tries to
713 /// find the shortest path (the one with lowest penalty) from \p InitialState
714 /// to a state where all tokens are placed.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000715 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000716 std::set<LineState> Seen;
717
Daniel Jasper4b866272013-02-01 11:00:45 +0000718 // Insert start element into queue.
Daniel Jasper687af3b2013-02-14 14:26:07 +0000719 StateNode *Node =
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000720 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
721 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
722 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000723
724 // While not empty, take first element and follow edges.
725 while (!Queue.empty()) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000726 unsigned Penalty = Queue.top().first.first;
Daniel Jasper687af3b2013-02-14 14:26:07 +0000727 StateNode *Node = Queue.top().second;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000728 if (Node->State.NextToken == NULL) {
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000729 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper4b866272013-02-01 11:00:45 +0000730 break;
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000731 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000732 Queue.pop();
Daniel Jasper4b866272013-02-01 11:00:45 +0000733
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000734 if (!Seen.insert(Node->State).second)
735 // State already examined with lower penalty.
736 continue;
Daniel Jasper4b866272013-02-01 11:00:45 +0000737
Manuel Klimekaf491072013-02-13 10:54:19 +0000738 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
739 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper4b866272013-02-01 11:00:45 +0000740 }
741
742 if (Queue.empty())
743 // We were unable to find a solution, do nothing.
744 // FIXME: Add diagnostic?
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 return 0;
746
Daniel Jasper4b866272013-02-01 11:00:45 +0000747 // Reconstruct the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000748 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000749 DEBUG(llvm::errs() << "---\n");
Daniel Jasperf7935112012-12-03 18:12:45 +0000750
Daniel Jasper4b866272013-02-01 11:00:45 +0000751 // Return the column after the last token of the solution.
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000752 return Queue.top().second->State.Column;
753 }
754
755 void reconstructPath(LineState &State, StateNode *Current) {
756 // FIXME: This recursive implementation limits the possible number
757 // of tokens per line if compiled into a binary with small stack space.
758 // To become more independent of stack frame limitations we would need
759 // to also change the TokenAnnotator.
760 if (Current->Previous == NULL)
761 return;
762 reconstructPath(State, Current->Previous);
763 DEBUG({
764 if (Current->NewLine) {
Daniel Jasperb9caeac2013-02-13 20:33:44 +0000765 llvm::errs()
766 << "Penalty for splitting before "
767 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
768 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000769 }
770 });
771 addTokenToState(Current->NewLine, false, State);
Daniel Jasper4b866272013-02-01 11:00:45 +0000772 }
773
Manuel Klimekaf491072013-02-13 10:54:19 +0000774 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper4b866272013-02-01 11:00:45 +0000775 ///
Manuel Klimekaf491072013-02-13 10:54:19 +0000776 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper4b866272013-02-01 11:00:45 +0000777 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimekaf491072013-02-13 10:54:19 +0000778 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
779 bool NewLine) {
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000780 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000781 return;
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000782 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper4b866272013-02-01 11:00:45 +0000783 return;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000784 if (NewLine)
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000785 Penalty += PreviousNode->State.NextToken->SplitPenalty;
786
787 StateNode *Node = new (Allocator.Allocate())
788 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek1998ea22013-02-20 10:15:13 +0000789 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000790 if (Node->State.Column > getColumnLimit()) {
791 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper3a9370c2013-02-04 07:21:18 +0000792 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasper2df93312013-01-09 10:16:05 +0000793 }
Manuel Klimek2ef908e2013-02-13 10:46:36 +0000794
795 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
796 ++Count;
Daniel Jasper4b866272013-02-01 11:00:45 +0000797 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000798
Daniel Jasper4b866272013-02-01 11:00:45 +0000799 /// \brief Returns \c true, if a line break after \p State is allowed.
800 bool canBreak(const LineState &State) {
801 if (!State.NextToken->CanBreakBefore &&
802 !(State.NextToken->is(tok::r_brace) &&
803 State.Stack.back().BreakBeforeClosingBrace))
804 return false;
Daniel Jaspercc960fa2013-04-22 07:59:53 +0000805 return !State.Stack.back().NoLineBreak;
Daniel Jasper4b866272013-02-01 11:00:45 +0000806 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000807
Daniel Jasper4b866272013-02-01 11:00:45 +0000808 /// \brief Returns \c true, if a line break after \p State is mandatory.
809 bool mustBreak(const LineState &State) {
810 if (State.NextToken->MustBreakBefore)
811 return true;
812 if (State.NextToken->is(tok::r_brace) &&
813 State.Stack.back().BreakBeforeClosingBrace)
814 return true;
815 if (State.NextToken->Parent->is(tok::semi) &&
816 State.LineContainsContinuedForLoopSection)
817 return true;
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000818 if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
Daniel Jaspercd8599e2013-02-23 21:01:55 +0000819 State.NextToken->is(tok::question) ||
820 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000821 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc04baae2013-04-10 09:49:49 +0000822 !State.NextToken->isTrailingComment() &&
Daniel Jasper37905f72013-02-21 15:00:29 +0000823 State.NextToken->isNot(tok::r_paren) &&
824 State.NextToken->isNot(tok::r_brace))
Daniel Jasper4b866272013-02-01 11:00:45 +0000825 return true;
Daniel Jasperacc33662013-02-08 08:22:00 +0000826 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
827 // out whether it is the first parameter. Clean this up.
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000828 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperacc33662013-02-08 08:22:00 +0000829 State.NextToken->LongestObjCSelectorName == 0 &&
830 State.Stack.back().BreakBeforeParameter)
Daniel Jasper1ac3e052013-02-05 10:07:47 +0000831 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000832 if ((State.NextToken->Type == TT_CtorInitializerColon ||
833 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper400adc62013-02-08 15:28:42 +0000834 State.ParenLevel == 0)))
Daniel Jasper4b866272013-02-01 11:00:45 +0000835 return true;
Daniel Jasper40aacf42013-03-14 13:45:21 +0000836 if (State.NextToken->Type == TT_InlineASMColon)
837 return true;
Daniel Jasper9b334242013-03-15 14:57:30 +0000838 // This prevents breaks like:
839 // ...
840 // SomeParameter, OtherParameter).DoSomething(
841 // ...
842 // As they hide "DoSomething" and generally bad for readability.
843 if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
844 getRemainingLength(State) + State.Column > getColumnLimit() &&
845 State.ParenLevel < State.StartOfLineLevel)
846 return true;
Daniel Jasper4b866272013-02-01 11:00:45 +0000847 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000848 }
849
Daniel Jasper9b334242013-03-15 14:57:30 +0000850 // Returns the total number of columns required for the remaining tokens.
851 unsigned getRemainingLength(const LineState &State) {
852 if (State.NextToken && State.NextToken->Parent)
853 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
854 return 0;
855 }
856
Daniel Jasperf7935112012-12-03 18:12:45 +0000857 FormatStyle Style;
858 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000859 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000860 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000861 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000862 WhitespaceManager &Whitespaces;
Manuel Klimekaf491072013-02-13 10:54:19 +0000863
864 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
865 QueueType Queue;
866 // Increasing count of \c StateNode items we have created. This is used
867 // to create a deterministic order independent of the container.
868 unsigned Count;
Daniel Jasperf7935112012-12-03 18:12:45 +0000869};
870
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000871class LexerBasedFormatTokenSource : public FormatTokenSource {
872public:
873 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000874 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000875 IdentTable(Lex.getLangOpts()) {
876 Lex.SetKeepWhitespaceMode(true);
877 }
878
879 virtual FormatToken getNextToken() {
880 if (GreaterStashed) {
881 FormatTok.NewlinesBefore = 0;
882 FormatTok.WhiteSpaceStart =
883 FormatTok.Tok.getLocation().getLocWithOffset(1);
884 FormatTok.WhiteSpaceLength = 0;
885 GreaterStashed = false;
886 return FormatTok;
887 }
888
889 FormatTok = FormatToken();
890 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000891 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000892 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000893 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
894 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000895
896 // Consume and record whitespace until we find a significant token.
897 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimek0c137952013-02-11 12:33:24 +0000898 unsigned Newlines = Text.count('\n');
Daniel Jasper973c9422013-03-04 13:43:19 +0000899 if (Newlines > 0)
900 FormatTok.LastNewlineOffset =
901 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimek0c137952013-02-11 12:33:24 +0000902 unsigned EscapedNewlines = Text.count("\\\n");
903 FormatTok.NewlinesBefore += Newlines;
904 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000905 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
906
907 if (FormatTok.Tok.is(tok::eof))
908 return FormatTok;
909 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +0000910 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000911 }
Manuel Klimekef920692013-01-07 07:56:50 +0000912
913 // Now FormatTok is the next non-whitespace token.
914 FormatTok.TokenLength = Text.size();
915
Alexander Kornienko9e90b622013-04-17 17:34:05 +0000916 if (FormatTok.Tok.is(tok::comment)) {
917 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
918 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
919 }
920
Manuel Klimek1abf7892013-01-04 23:34:14 +0000921 // In case the token starts with escaped newlines, we want to
922 // take them into account as whitespace - this pattern is quite frequent
923 // in macro definitions.
924 // FIXME: What do we want to do with other escaped spaces, and escaped
925 // spaces or newlines in the middle of tokens?
926 // FIXME: Add a more explicit test.
927 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000928 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000929 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +0000930 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +0000931 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000932 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000933 }
934
935 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000936 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +0000937 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000938 FormatTok.Tok.setKind(Info.getTokenID());
939 }
940
941 if (FormatTok.Tok.is(tok::greatergreater)) {
942 FormatTok.Tok.setKind(tok::greater);
Daniel Jasper57d4a582013-02-28 10:06:05 +0000943 FormatTok.TokenLength = 1;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000944 GreaterStashed = true;
945 }
946
947 return FormatTok;
948 }
949
Nico Weber29f9dea2013-02-11 15:32:15 +0000950 IdentifierTable &getIdentTable() { return IdentTable; }
951
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000952private:
953 FormatToken FormatTok;
954 bool GreaterStashed;
955 Lexer &Lex;
956 SourceManager &SourceMgr;
957 IdentifierTable IdentTable;
958
959 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +0000960 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000961 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
962 Tok.getLength());
963 }
964};
965
Daniel Jasperf7935112012-12-03 18:12:45 +0000966class Formatter : public UnwrappedLineConsumer {
967public:
Daniel Jasper25837aa2013-01-14 14:14:23 +0000968 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
969 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +0000970 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +0000971 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoafcef332013-03-19 17:41:36 +0000972 Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000973
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000974 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000975
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000976 tooling::Replacements format() {
977 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
978 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Manuel Klimek1a18c402013-04-12 14:13:36 +0000979 bool StructuralError = Parser.parse();
Alexander Kornienko62b85b92013-03-13 14:41:29 +0000980 unsigned PreviousEndOfLineColumn = 0;
981 TokenAnnotator Annotator(Style, SourceMgr, Lex,
982 Tokens.getIdentTable().get("in"));
983 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
984 Annotator.annotate(AnnotatedLines[i]);
985 }
986 deriveLocalStyle();
987 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
988 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
989 }
Daniel Jasperb67cc422013-04-09 17:46:55 +0000990
991 // Adapt level to the next line if this is a comment.
992 // FIXME: Can/should this be done in the UnwrappedLineParser?
Daniel Jasper6728fc12013-04-11 14:29:13 +0000993 const AnnotatedLine *NextNoneCommentLine = NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +0000994 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
995 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
996 AnnotatedLines[i].First.Children.empty())
997 AnnotatedLines[i].Level = NextNoneCommentLine->Level;
998 else
Alexander Kornienkocb45bc12013-04-15 14:28:00 +0000999 NextNoneCommentLine =
1000 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
1001 : NULL;
Daniel Jasperb67cc422013-04-09 17:46:55 +00001002 }
1003
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001004 std::vector<int> IndentForLevel;
1005 bool PreviousLineWasTouched = false;
Alexander Kornienkofd433362013-03-27 17:08:02 +00001006 const AnnotatedToken *PreviousLineLastToken = 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001007 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1008 E = AnnotatedLines.end();
1009 I != E; ++I) {
1010 const AnnotatedLine &TheLine = *I;
1011 const FormatToken &FirstTok = TheLine.First.FormatTok;
1012 int Offset = getIndentOffset(TheLine.First);
1013 while (IndentForLevel.size() <= TheLine.Level)
1014 IndentForLevel.push_back(-1);
1015 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasperd1ae3582013-03-20 12:37:50 +00001016 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001017 if (TheLine.First.is(tok::eof)) {
1018 if (PreviousLineWasTouched) {
1019 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
1020 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001021 /*WhitespaceStartColumn*/ 0);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001022 }
1023 } else if (TheLine.Type != LT_Invalid &&
1024 (WasMoved || touchesLine(TheLine))) {
1025 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
1026 unsigned Indent = LevelIndent;
1027 if (static_cast<int>(Indent) + Offset >= 0)
1028 Indent += Offset;
Manuel Klimek1a18c402013-04-12 14:13:36 +00001029 if (FirstTok.WhiteSpaceStart.isValid() &&
1030 // Insert a break even if there is a structural error in case where
1031 // we break apart a line consisting of multiple unwrapped lines.
1032 (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001033 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1034 TheLine.InPPDirective, PreviousEndOfLineColumn);
Manuel Klimek1a18c402013-04-12 14:13:36 +00001035 } else {
1036 Indent = LevelIndent =
1037 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001038 }
1039 tryFitMultipleLinesInOne(Indent, I, E);
1040 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Manuel Klimek1a18c402013-04-12 14:13:36 +00001041 TheLine.First, Whitespaces);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001042 PreviousEndOfLineColumn =
1043 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
1044 IndentForLevel[TheLine.Level] = LevelIndent;
1045 PreviousLineWasTouched = true;
1046 } else {
1047 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
1048 unsigned Indent =
1049 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
1050 unsigned LevelIndent = Indent;
1051 if (static_cast<int>(LevelIndent) - Offset >= 0)
1052 LevelIndent -= Offset;
Daniel Jasper66dc2ec2013-03-20 14:31:47 +00001053 if (TheLine.First.isNot(tok::comment))
1054 IndentForLevel[TheLine.Level] = LevelIndent;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001055
1056 // Remove trailing whitespace of the previous line if it was touched.
1057 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Alexander Kornienkofd433362013-03-27 17:08:02 +00001058 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
1059 TheLine.InPPDirective, PreviousEndOfLineColumn);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001060 }
1061 // If we did not reformat this unwrapped line, the column at the end of
1062 // the last token is unchanged - thus, we can calculate the end of the
1063 // last token.
1064 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
1065 PreviousEndOfLineColumn =
1066 SourceMgr.getSpellingColumnNumber(LastLoc) +
1067 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
1068 PreviousLineWasTouched = false;
Daniel Jasperbc0fa392013-03-22 16:25:51 +00001069 if (TheLine.Last->is(tok::comment))
1070 Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
1071 TheLine.Last->FormatTok.Tok.getLocation()) - 1);
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001072 }
Alexander Kornienkofd433362013-03-27 17:08:02 +00001073 PreviousLineLastToken = I->Last;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001074 }
1075 return Whitespaces.generateReplacements();
1076 }
1077
1078private:
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001079 void deriveLocalStyle() {
1080 unsigned CountBoundToVariable = 0;
1081 unsigned CountBoundToType = 0;
1082 bool HasCpp03IncompatibleFormat = false;
1083 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1084 if (AnnotatedLines[i].First.Children.empty())
1085 continue;
1086 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1087 while (!Tok->Children.empty()) {
1088 if (Tok->Type == TT_PointerOrReference) {
1089 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1090 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1091 if (SpacesBefore && !SpacesAfter)
1092 ++CountBoundToVariable;
1093 else if (!SpacesBefore && SpacesAfter)
1094 ++CountBoundToType;
1095 }
1096
Daniel Jasper400adc62013-02-08 15:28:42 +00001097 if (Tok->Type == TT_TemplateCloser &&
1098 Tok->Parent->Type == TT_TemplateCloser &&
1099 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper7fce3ab2013-02-06 14:22:40 +00001100 HasCpp03IncompatibleFormat = true;
1101 Tok = &Tok->Children[0];
1102 }
1103 }
1104 if (Style.DerivePointerBinding) {
1105 if (CountBoundToType > CountBoundToVariable)
1106 Style.PointerBindsToType = true;
1107 else if (CountBoundToType < CountBoundToVariable)
1108 Style.PointerBindsToType = false;
1109 }
1110 if (Style.Standard == FormatStyle::LS_Auto) {
1111 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1112 : FormatStyle::LS_Cpp03;
1113 }
1114 }
1115
Manuel Klimekb95f5452013-02-08 17:38:27 +00001116 /// \brief Get the indent of \p Level from \p IndentForLevel.
1117 ///
1118 /// \p IndentForLevel must contain the indent for the level \c l
1119 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1120 /// that level is unknown.
Daniel Jasper687af3b2013-02-14 14:26:07 +00001121 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimekb95f5452013-02-08 17:38:27 +00001122 if (IndentForLevel[Level] != -1)
1123 return IndentForLevel[Level];
Manuel Klimekd076dcd2013-02-08 19:53:32 +00001124 if (Level == 0)
1125 return 0;
Daniel Jasper24570102013-02-14 09:58:41 +00001126 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimekb95f5452013-02-08 17:38:27 +00001127 }
1128
1129 /// \brief Get the offset of the line relatively to the level.
1130 ///
1131 /// For example, 'public:' labels in classes are offset by 1 or 2
1132 /// characters to the left from their level.
Daniel Jasper24570102013-02-14 09:58:41 +00001133 int getIndentOffset(const AnnotatedToken &RootToken) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001134 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
Manuel Klimekb95f5452013-02-08 17:38:27 +00001135 return Style.AccessModifierOffset;
1136 return 0;
1137 }
1138
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001139 /// \brief Tries to merge lines into one.
1140 ///
1141 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1142 /// if possible; note that \c I will be incremented when lines are merged.
1143 ///
1144 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001145 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001146 std::vector<AnnotatedLine>::iterator &I,
1147 std::vector<AnnotatedLine>::iterator E) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001148 // We can never merge stuff if there are trailing line comments.
1149 if (I->Last->Type == TT_LineComment)
1150 return;
1151
Daniel Jasperc22f5b42013-02-28 11:05:57 +00001152 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001153 // If we already exceed the column limit, we set 'Limit' to 0. The different
1154 // tryMerge..() functions can then decide whether to still do merging.
1155 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001156
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001157 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001158 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001159
Daniel Jasper25837aa2013-01-14 14:14:23 +00001160 if (I->Last->is(tok::l_brace)) {
1161 tryMergeSimpleBlock(I, E, Limit);
1162 } else if (I->First.is(tok::kw_if)) {
1163 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001164 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1165 I->First.FormatTok.IsFirst)) {
1166 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001167 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001168 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001169 }
1170
Daniel Jasper39825ea2013-01-14 15:40:57 +00001171 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1172 std::vector<AnnotatedLine>::iterator E,
1173 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001174 if (Limit == 0)
1175 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001176 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001177 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1178 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001179 if (I + 2 != E && (I + 2)->InPPDirective &&
1180 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1181 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001182 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001183 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001184 join(Line, *(++I));
1185 }
1186
Daniel Jasper25837aa2013-01-14 14:14:23 +00001187 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1188 std::vector<AnnotatedLine>::iterator E,
1189 unsigned Limit) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001190 if (Limit == 0)
1191 return;
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001192 if (!Style.AllowShortIfStatementsOnASingleLine)
1193 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001194 if ((I + 1)->InPPDirective != I->InPPDirective ||
1195 ((I + 1)->InPPDirective &&
1196 (I + 1)->First.FormatTok.HasUnescapedNewline))
1197 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001198 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001199 if (Line.Last->isNot(tok::r_paren))
1200 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001201 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001202 return;
1203 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1204 return;
1205 // Only inline simple if's (no nested if or else).
1206 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1207 return;
1208 join(Line, *(++I));
1209 }
1210
1211 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001212 std::vector<AnnotatedLine>::iterator E,
1213 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001214 // First, check that the current line allows merging. This is the case if
1215 // we're not in a control flow statement and the last token is an opening
1216 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001217 AnnotatedLine &Line = *I;
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001218 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
1219 tok::kw_else, tok::kw_try, tok::kw_catch,
1220 tok::kw_for,
1221 // This gets rid of all ObjC @ keywords and methods.
1222 tok::at, tok::minus, tok::plus))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001223 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001224
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001225 AnnotatedToken *Tok = &(I + 1)->First;
1226 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001227 !Tok->MustBreakBefore) {
1228 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jaspereef30492013-02-11 12:36:37 +00001229 Tok->SpacesRequiredBefore = 0;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001230 Tok->CanBreakBefore = true;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001231 join(Line, *(I + 1));
1232 I += 1;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001233 } else if (Limit != 0) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001234 // Check that we still have three lines and they fit into the limit.
1235 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1236 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001237 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001238
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001239 // Second, check that the next line does not contain any braces - if it
1240 // does, readability declines when putting it into a single line.
1241 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1242 return;
1243 do {
Alexander Kornienko62b85b92013-03-13 14:41:29 +00001244 if (Tok->isOneOf(tok::l_brace, tok::r_brace))
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001245 return;
1246 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1247 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001248
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001249 // Last, check that the third line contains a single closing brace.
1250 Tok = &(I + 2)->First;
1251 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1252 Tok->MustBreakBefore)
1253 return;
1254
1255 join(Line, *(I + 1));
1256 join(Line, *(I + 2));
1257 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001258 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001259 }
1260
1261 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1262 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001263 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1264 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001265 }
1266
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001268 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001269 A.Last->Children.push_back(B.First);
1270 while (!A.Last->Children.empty()) {
1271 A.Last->Children[0].Parent = A.Last;
Daniel Jasper12ef4e52013-02-21 21:33:55 +00001272 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001273 A.Last = &A.Last->Children[0];
1274 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001275 }
1276
Daniel Jasper97b89482013-03-13 07:49:51 +00001277 bool touchesRanges(const CharSourceRange &Range) {
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001278 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1279 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1280 Ranges[i].getBegin()) &&
1281 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1282 Range.getBegin()))
1283 return true;
1284 }
1285 return false;
1286 }
1287
1288 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001289 const FormatToken *First = &TheLine.First.FormatTok;
1290 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001291 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper973c9422013-03-04 13:43:19 +00001292 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1293 Last->Tok.getLocation());
Daniel Jasperf71cf3b2013-03-07 20:50:00 +00001294 return touchesRanges(LineRange);
1295 }
1296
1297 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1298 const FormatToken *First = &TheLine.First.FormatTok;
1299 CharSourceRange LineRange = CharSourceRange::getCharRange(
1300 First->WhiteSpaceStart,
1301 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1302 return touchesRanges(LineRange);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001303 }
1304
1305 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001306 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001307 }
1308
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001309 /// \brief Add a new line and the required indent before the first Token
1310 /// of the \c UnwrappedLine if there was no structural parsing error.
1311 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkofd433362013-03-27 17:08:02 +00001312 void formatFirstToken(const AnnotatedToken &RootToken,
1313 const AnnotatedToken *PreviousToken, unsigned Indent,
Manuel Klimekb95f5452013-02-08 17:38:27 +00001314 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001315 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001316
Daniel Jasperbbc84152013-01-29 11:27:30 +00001317 unsigned Newlines =
1318 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001319 if (Newlines == 0 && !Tok.IsFirst)
1320 Newlines = 1;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001321
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001322 if (!InPPDirective || Tok.HasUnescapedNewline) {
Alexander Kornienkofd433362013-03-27 17:08:02 +00001323 // Insert extra new line before access specifiers.
1324 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
1325 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
1326 ++Newlines;
1327
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001328 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001329 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001330 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
Alexander Kornienkoafcef332013-03-19 17:41:36 +00001331 PreviousEndOfLineColumn);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001332 }
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001333 }
1334
Alexander Kornienko116ba682013-01-14 11:34:14 +00001335 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001336 FormatStyle Style;
1337 Lexer &Lex;
1338 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001339 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001340 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001341 std::vector<AnnotatedLine> AnnotatedLines;
Daniel Jasperf7935112012-12-03 18:12:45 +00001342};
1343
Alexander Kornienkocb45bc12013-04-15 14:28:00 +00001344tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1345 SourceManager &SourceMgr,
1346 std::vector<CharSourceRange> Ranges,
1347 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001348 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001349 OwningPtr<DiagnosticConsumer> DiagPrinter;
1350 if (DiagClient == 0) {
1351 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1352 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1353 DiagClient = DiagPrinter.get();
1354 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001355 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001356 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001357 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001358 Diagnostics.setSourceManager(&SourceMgr);
1359 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001360 return formatter.format();
1361}
1362
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001363LangOptions getFormattingLangOpts() {
1364 LangOptions LangOpts;
1365 LangOpts.CPlusPlus = 1;
1366 LangOpts.CPlusPlus11 = 1;
Daniel Jasper55213652013-03-22 10:01:29 +00001367 LangOpts.LineComment = 1;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001368 LangOpts.Bool = 1;
1369 LangOpts.ObjC1 = 1;
1370 LangOpts.ObjC2 = 1;
1371 return LangOpts;
1372}
1373
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001374} // namespace format
1375} // namespace clang