blob: e738a5c3f3f3c1cdc4a6cb7837dd269b5bed865e [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
Daniel Jasper32d28ee2013-01-29 21:01:14 +000018#include "TokenAnnotator.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000020#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000023#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000026#include "llvm/Support/Allocator.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000027#include "llvm/Support/Debug.h"
Manuel Klimek32a2fd72013-02-13 10:46:36 +000028#include <queue>
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Daniel Jasperbac016b2012-12-03 18:12:45 +000031namespace clang {
32namespace format {
33
Daniel Jasperbac016b2012-12-03 18:12:45 +000034FormatStyle getLLVMStyle() {
35 FormatStyle LLVMStyle;
36 LLVMStyle.ColumnLimit = 80;
37 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000038 LLVMStyle.PointerBindsToType = false;
39 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000040 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000041 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000042 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000043 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000044 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000045 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000046 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000047 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000048 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000049 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jaspera03ab102013-02-13 20:33:44 +000050 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
Daniel Jasperbac016b2012-12-03 18:12:45 +000051 return LLVMStyle;
52}
53
54FormatStyle getGoogleStyle() {
55 FormatStyle GoogleStyle;
56 GoogleStyle.ColumnLimit = 80;
57 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000058 GoogleStyle.PointerBindsToType = true;
59 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000060 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000061 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000062 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000063 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000064 GoogleStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000066 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000067 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000068 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000069 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jaspera03ab102013-02-13 20:33:44 +000070 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
Daniel Jasperbac016b2012-12-03 18:12:45 +000071 return GoogleStyle;
72}
73
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000074FormatStyle getChromiumStyle() {
75 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000076 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperfaab0d32013-02-27 09:47:53 +000077 ChromiumStyle.BinPackParameters = false;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000078 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
79 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000080 return ChromiumStyle;
81}
82
Daniel Jasper15417ef2013-02-06 20:07:35 +000083static bool isTrailingComment(const AnnotatedToken &Tok) {
84 return Tok.is(tok::comment) &&
85 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
86}
87
Daniel Jasperce3d1a62013-02-08 08:22:00 +000088// Returns the length of everything up to the first possible line break after
89// the ), ], } or > matching \c Tok.
90static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
91 if (Tok.MatchingParen == NULL)
92 return 0;
93 AnnotatedToken *End = Tok.MatchingParen;
94 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
95 End = &End->Children[0];
96 }
97 return End->TotalLength - Tok.TotalLength + 1;
98}
99
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000100/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000101///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000102/// This includes special handling for certain constructs, e.g. the alignment of
103/// trailing line comments.
104class WhitespaceManager {
105public:
106 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
107
108 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
109 /// each \c AnnotatedToken.
110 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
111 unsigned Spaces, unsigned WhitespaceStartColumn,
112 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000113 // 2+ newlines mean an empty line separating logic scopes.
114 if (NewLines >= 2)
115 alignComments();
116
117 // Align line comments if they are trailing or if they continue other
118 // trailing comments.
Daniel Jasper812c0452013-03-01 16:45:59 +0000119 if (isTrailingComment(Tok)) {
120 // Remove the comment's trailing whitespace.
121 if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
122 Replaces.insert(tooling::Replacement(
123 SourceMgr, Tok.FormatTok.Tok.getLocation().getLocWithOffset(
124 Tok.FormatTok.TokenLength),
125 Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
126
127 // Align comment with other comments.
128 if (Tok.Parent != NULL || !Comments.empty()) {
129 if (Style.ColumnLimit >=
130 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
131 Comments.push_back(StoredComment());
132 Comments.back().Tok = Tok.FormatTok;
133 Comments.back().Spaces = Spaces;
134 Comments.back().NewLines = NewLines;
135 if (NewLines == 0)
136 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
137 else
138 Comments.back().MinColumn = Spaces;
139 Comments.back().MaxColumn =
140 Style.ColumnLimit - Tok.FormatTok.TokenLength;
141 return;
142 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000143 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000144 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000145
146 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000147 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000148 alignComments();
Manuel Klimek8092a942013-02-20 10:15:13 +0000149 storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000150 }
151
152 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
153 /// backslashes to escape newlines inside a preprocessor directive.
154 ///
155 /// This function and \c replaceWhitespace have the same behavior if
156 /// \c Newlines == 0.
157 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
158 unsigned Spaces, unsigned WhitespaceStartColumn,
159 const FormatStyle &Style) {
Manuel Klimek8092a942013-02-20 10:15:13 +0000160 storeReplacement(
161 Tok.FormatTok,
162 getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style));
163 }
164
165 /// \brief Inserts a line break into the middle of a token.
166 ///
167 /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
168 /// break and \p Postfix before the rest of the token starts in the next line.
169 ///
170 /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
171 /// used to generate the correct line break.
172 void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix,
173 StringRef Postfix, bool InPPDirective, unsigned Spaces,
174 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
175 std::string NewLineText;
176 if (!InPPDirective)
177 NewLineText = getNewLineText(1, Spaces);
178 else
179 NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style);
180 std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
181 SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart
182 .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset);
183 Replaces.insert(
184 tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText));
185 }
186
187 /// \brief Returns all the \c Replacements created during formatting.
188 const tooling::Replacements &generateReplacements() {
189 alignComments();
190 return Replaces;
191 }
192
193private:
194 std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
195 return std::string(NewLines, '\n') + std::string(Spaces, ' ');
196 }
197
198 std::string
199 getNewLineText(unsigned NewLines, unsigned Spaces,
200 unsigned WhitespaceStartColumn, const FormatStyle &Style) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000201 std::string NewLineText;
202 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000203 unsigned Offset =
204 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000205 for (unsigned i = 0; i < NewLines; ++i) {
206 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
207 NewLineText += "\\\n";
208 Offset = 0;
209 }
210 }
Manuel Klimek8092a942013-02-20 10:15:13 +0000211 return NewLineText + std::string(Spaces, ' ');
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000212 }
213
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000214 /// \brief Structure to store a comment for later layout and alignment.
215 struct StoredComment {
216 FormatToken Tok;
217 unsigned MinColumn;
218 unsigned MaxColumn;
219 unsigned NewLines;
220 unsigned Spaces;
221 };
222 SmallVector<StoredComment, 16> Comments;
223 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
224
225 /// \brief Try to align all stashed comments.
226 void alignComments() {
227 unsigned MinColumn = 0;
228 unsigned MaxColumn = UINT_MAX;
229 comment_iterator Start = Comments.begin();
230 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
231 ++I) {
232 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
233 alignComments(Start, I, MinColumn);
234 MinColumn = I->MinColumn;
235 MaxColumn = I->MaxColumn;
236 Start = I;
237 } else {
238 MinColumn = std::max(MinColumn, I->MinColumn);
239 MaxColumn = std::min(MaxColumn, I->MaxColumn);
240 }
241 }
242 alignComments(Start, Comments.end(), MinColumn);
243 Comments.clear();
244 }
245
246 /// \brief Put all the comments between \p I and \p E into \p Column.
247 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
248 while (I != E) {
249 unsigned Spaces = I->Spaces + Column - I->MinColumn;
250 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper29f123b2013-02-08 15:28:42 +0000251 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000252 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000253 }
254 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000255
256 /// \brief Stores \p Text as the replacement for the whitespace in front of
257 /// \p Tok.
258 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000259 // Don't create a replacement, if it does not change anything.
260 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
261 Tok.WhiteSpaceLength) == Text)
262 return;
263
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000264 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
265 Tok.WhiteSpaceLength, Text));
266 }
267
268 SourceManager &SourceMgr;
269 tooling::Replacements Replaces;
270};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000271
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272class UnwrappedLineFormatter {
273public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000274 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000275 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000276 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000277 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000278 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000279 FirstIndent(FirstIndent), RootToken(RootToken),
Daniel Jasperf11a7052013-02-21 21:33:55 +0000280 Whitespaces(Whitespaces), Count(0) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000281
Manuel Klimekd4397b92013-01-04 23:34:14 +0000282 /// \brief Formats an \c UnwrappedLine.
283 ///
284 /// \returns The column after the last token in the last line of the
285 /// \c UnwrappedLine.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000286 unsigned format(const AnnotatedLine *NextLine) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000287 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000288 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000289 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000290 State.NextToken = &RootToken;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000291 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent,
292 !Style.BinPackParameters,
293 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000294 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000295 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000296 State.ParenLevel = 0;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000297 State.StartOfStringLiteral = 0;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000298 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000299
Manuel Klimekca547db2013-01-16 14:55:28 +0000300 DEBUG({
301 DebugTokenState(*State.NextToken);
302 });
303
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000304 // The first token has already been indented and thus consumed.
Manuel Klimek8092a942013-02-20 10:15:13 +0000305 moveStateToNextToken(State, /*DryRun=*/ false);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000306
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000307 // If everything fits on a single line, just put it there.
Daniel Jaspera4d46212013-02-28 11:05:57 +0000308 unsigned ColumnLimit = Style.ColumnLimit;
309 if (NextLine && NextLine->InPPDirective &&
310 !NextLine->First.FormatTok.HasUnescapedNewline)
311 ColumnLimit = getColumnLimit();
312 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000313 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000314 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000315 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000316 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000317 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000318
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000319 // If the ObjC method declaration does not fit on a line, we should format
320 // it with one arg per line.
321 if (Line.Type == LT_ObjCMethodDecl)
322 State.Stack.back().BreakBeforeParameter = true;
323
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000324 // Find best solution in solution space.
325 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000326 }
327
328private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000329 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
330 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000331 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
332 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000333 llvm::errs();
334 }
335
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000336 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000337 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
338 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000339 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
340 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000341 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper24849712013-03-01 16:48:32 +0000342 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
343 StartOfFunctionCall(0) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000344
Daniel Jasperbac016b2012-12-03 18:12:45 +0000345 /// \brief The position to which a specific parenthesis level needs to be
346 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000347 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000348
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000349 /// \brief The position of the last space on each level.
350 ///
351 /// Used e.g. to break like:
352 /// functionCall(Parameter, otherCall(
353 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000354 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000355
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000356 /// \brief The position the first "<<" operator encountered on each level.
357 ///
358 /// Used to align "<<" operators. 0 if no such operator has been encountered
359 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000360 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000361
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000362 /// \brief Whether a newline needs to be inserted before the block's closing
363 /// brace.
364 ///
365 /// We only want to insert a newline before the closing brace if there also
366 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000367 bool BreakBeforeClosingBrace;
368
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000369 /// \brief The column of a \c ? in a conditional expression;
370 unsigned QuestionColumn;
371
Daniel Jasperf343cab2013-01-31 14:59:26 +0000372 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
373 /// lines, in this context.
374 bool AvoidBinPacking;
375
376 /// \brief Break after the next comma (or all the commas in this context if
377 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000378 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000379
380 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000381 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000382
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000383 /// \brief The position of the colon in an ObjC method declaration/call.
384 unsigned ColonPos;
Daniel Jasperc4615b72013-02-20 12:56:39 +0000385
Daniel Jasper24849712013-03-01 16:48:32 +0000386 /// \brief The start of the most recent function in a builder-type call.
387 unsigned StartOfFunctionCall;
388
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000389 bool operator<(const ParenState &Other) const {
390 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000391 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000392 if (LastSpace != Other.LastSpace)
393 return LastSpace < Other.LastSpace;
394 if (FirstLessLess != Other.FirstLessLess)
395 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000396 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
397 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000398 if (QuestionColumn != Other.QuestionColumn)
399 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000400 if (AvoidBinPacking != Other.AvoidBinPacking)
401 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000402 if (BreakBeforeParameter != Other.BreakBeforeParameter)
403 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000404 if (HasMultiParameterLine != Other.HasMultiParameterLine)
405 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000406 if (ColonPos != Other.ColonPos)
407 return ColonPos < Other.ColonPos;
Daniel Jasper24849712013-03-01 16:48:32 +0000408 if (StartOfFunctionCall != Other.StartOfFunctionCall)
409 return StartOfFunctionCall < Other.StartOfFunctionCall;
Daniel Jasperb3123142013-01-12 07:36:22 +0000410 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000411 }
412 };
413
414 /// \brief The current state when indenting a unwrapped line.
415 ///
416 /// As the indenting tries different combinations this is copied by value.
417 struct LineState {
418 /// \brief The number of used columns in the current line.
419 unsigned Column;
420
421 /// \brief The token that needs to be next formatted.
422 const AnnotatedToken *NextToken;
423
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000424 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000425 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000426 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000427 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000428
429 /// \brief \c true if this line contains a continued for-loop section.
430 bool LineContainsContinuedForLoopSection;
431
Daniel Jasper29f123b2013-02-08 15:28:42 +0000432 /// \brief The level of nesting inside (), [], <> and {}.
433 unsigned ParenLevel;
434
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000435 /// \brief The \c ParenLevel at the start of this line.
436 unsigned StartOfLineLevel;
437
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000438 /// \brief The start column of the string literal, if we're in a string
439 /// literal sequence, 0 otherwise.
440 unsigned StartOfStringLiteral;
441
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000442 /// \brief A stack keeping track of properties applying to parenthesis
443 /// levels.
444 std::vector<ParenState> Stack;
445
446 /// \brief Comparison operator to be able to used \c LineState in \c map.
447 bool operator<(const LineState &Other) const {
Daniel Jasperd7896702013-02-19 09:28:55 +0000448 if (NextToken != Other.NextToken)
449 return NextToken < Other.NextToken;
450 if (Column != Other.Column)
451 return Column < Other.Column;
452 if (VariablePos != Other.VariablePos)
453 return VariablePos < Other.VariablePos;
454 if (LineContainsContinuedForLoopSection !=
455 Other.LineContainsContinuedForLoopSection)
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000456 return LineContainsContinuedForLoopSection;
Daniel Jasperd7896702013-02-19 09:28:55 +0000457 if (ParenLevel != Other.ParenLevel)
458 return ParenLevel < Other.ParenLevel;
459 if (StartOfLineLevel != Other.StartOfLineLevel)
460 return StartOfLineLevel < Other.StartOfLineLevel;
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000461 if (StartOfStringLiteral != Other.StartOfStringLiteral)
462 return StartOfStringLiteral < Other.StartOfStringLiteral;
Daniel Jasperd7896702013-02-19 09:28:55 +0000463 return Stack < Other.Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000464 }
465 };
466
Daniel Jasper20409152012-12-04 14:54:30 +0000467 /// \brief Appends the next token to \p State and updates information
468 /// necessary for indentation.
469 ///
470 /// Puts the token on the current line if \p Newline is \c true and adds a
471 /// line break and necessary indentation otherwise.
472 ///
473 /// If \p DryRun is \c false, also creates and stores the required
474 /// \c Replacement.
Manuel Klimek8092a942013-02-20 10:15:13 +0000475 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000476 const AnnotatedToken &Current = *State.NextToken;
477 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000478 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000479
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000480 if (Current.Type == TT_ImplicitStringLiteral) {
481 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
482 State.NextToken->FormatTok.TokenLength;
483 if (State.NextToken->Children.empty())
484 State.NextToken = NULL;
485 else
486 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek8092a942013-02-20 10:15:13 +0000487 return 0;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000488 }
489
Daniel Jasperbac016b2012-12-03 18:12:45 +0000490 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000491 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000492 if (Current.is(tok::r_brace)) {
493 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000494 } else if (Current.is(tok::string_literal) &&
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000495 State.StartOfStringLiteral != 0) {
496 State.Column = State.StartOfStringLiteral;
Daniel Jasper66d19bd2013-02-18 11:59:17 +0000497 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000498 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000499 State.Stack.back().FirstLessLess != 0) {
500 State.Column = State.Stack.back().FirstLessLess;
501 } else if (State.ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000502 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000503 Current.is(tok::period) || Current.is(tok::arrow) ||
504 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000505 // Indent and extra 4 spaces after if we know the current expression is
506 // continued. Don't do that on the top level, as we already indent 4
507 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000508 State.Column = std::max(State.Stack.back().LastSpace,
509 State.Stack.back().Indent) + 4;
510 } else if (Current.Type == TT_ConditionalExpr) {
511 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000512 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000513 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
514 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000515 State.Column = State.VariablePos;
Daniel Jasper3c08a812013-02-24 18:54:32 +0000516 } else if (Previous.ClosesTemplateDeclaration ||
517 (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000518 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000519 } else if (Current.Type == TT_ObjCSelectorName) {
520 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
521 State.Column =
522 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
523 } else {
524 State.Column = State.Stack.back().Indent;
525 State.Stack.back().ColonPos =
526 State.Column + Current.FormatTok.TokenLength;
527 }
Daniel Jasper3c08a812013-02-24 18:54:32 +0000528 } else if (Previous.Type == TT_ObjCMethodExpr ||
529 Current.Type == TT_StartOfName) {
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000530 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000531 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000532 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000533 }
534
Daniel Jasper7878a7b2013-02-15 11:07:25 +0000535 if (Current.is(tok::question))
Daniel Jasper237d4c12013-02-23 21:01:55 +0000536 State.Stack.back().BreakBeforeParameter = true;
537 if ((Previous.is(tok::comma) || Previous.is(tok::semi)) &&
538 !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000539 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000540
Manuel Klimek060143e2013-01-02 18:33:23 +0000541 if (!DryRun) {
Daniel Jasper1ef81d52013-02-26 13:10:34 +0000542 unsigned NewLines = 1;
543 if (Current.Type == TT_LineComment)
544 NewLines =
545 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
546 Style.MaxEmptyLinesToKeep + 1));
Manuel Klimek060143e2013-01-02 18:33:23 +0000547 if (!Line.InPPDirective)
Daniel Jasperc4615b72013-02-20 12:56:39 +0000548 Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000549 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000550 else
Daniel Jasperc4615b72013-02-20 12:56:39 +0000551 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000552 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000553 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000554
Daniel Jasper29f123b2013-02-08 15:28:42 +0000555 State.Stack.back().LastSpace = State.Column;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000556 State.StartOfLineLevel = State.ParenLevel;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000557 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000558 State.Stack.back().Indent += 2;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000559
560 // Any break on this level means that the parent level has been broken
561 // and we need to avoid bin packing there.
562 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
563 State.Stack[i].BreakBeforeParameter = true;
564 }
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000565 if (Current.is(tok::period) || Current.is(tok::arrow))
566 State.Stack.back().BreakBeforeParameter = true;
567
Daniel Jasper237d4c12013-02-23 21:01:55 +0000568 // If we break after {, we should also break before the corresponding }.
569 if (Previous.is(tok::l_brace))
570 State.Stack.back().BreakBeforeClosingBrace = true;
571
572 if (State.Stack.back().AvoidBinPacking) {
573 // If we are breaking after '(', '{', '<', this is not bin packing
574 // unless AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper3c08a812013-02-24 18:54:32 +0000575 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
Daniel Jasper237d4c12013-02-23 21:01:55 +0000576 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
577 Line.MustBeDeclaration))
578 State.Stack.back().BreakBeforeParameter = true;
579 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000580 } else {
Daniel Jasper9c3e71a2013-02-25 15:59:54 +0000581 // FIXME: Put VariablePos into ParenState and remove second part of if().
582 if (Current.is(tok::equal) &&
583 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000584 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000585
Daniel Jasper729a7432013-02-11 12:36:37 +0000586 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000587
Daniel Jasperbac016b2012-12-03 18:12:45 +0000588 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000589 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000590
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000591 if (Current.Type == TT_ObjCSelectorName &&
592 State.Stack.back().ColonPos == 0) {
593 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
594 State.Column + Spaces + Current.FormatTok.TokenLength)
595 State.Stack.back().ColonPos =
596 State.Stack.back().Indent + Current.LongestObjCSelectorName;
597 else
598 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000599 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000600 }
601
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000602 if (Current.Type != TT_LineComment &&
603 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
604 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000605 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000606 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000607 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000608
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000609 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000610 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
611 // Treat the condition inside an if as if it was a second function
612 // parameter, i.e. let nested calls have an indent of 4.
613 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000614 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000615 // Top-level spaces are exempt as that mostly leads to better results.
616 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000617 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000618 Previous.Type == TT_ConditionalExpr ||
619 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000620 getPrecedence(Previous) != prec::Assignment)
621 State.Stack.back().LastSpace = State.Column;
Daniel Jasper6cabab42013-02-14 08:42:54 +0000622 else if (Previous.Type == TT_InheritanceColon)
623 State.Stack.back().Indent = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000624 else if (Previous.ParameterCount > 1 &&
625 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000626 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000627 Previous.Type == TT_TemplateOpener))
628 // If this function has multiple parameters, indent nested calls from
629 // the start of the first parameter.
630 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000631 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000632
Manuel Klimek8092a942013-02-20 10:15:13 +0000633 return moveStateToNextToken(State, DryRun);
Daniel Jasper20409152012-12-04 14:54:30 +0000634 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000635
Daniel Jasper20409152012-12-04 14:54:30 +0000636 /// \brief Mark the next token as consumed in \p State and modify its stacks
637 /// accordingly.
Manuel Klimek8092a942013-02-20 10:15:13 +0000638 unsigned moveStateToNextToken(LineState &State, bool DryRun) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000639 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000640 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000641
Daniel Jasper6cabab42013-02-14 08:42:54 +0000642 if (Current.Type == TT_InheritanceColon)
643 State.Stack.back().AvoidBinPacking = true;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000644 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
645 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000646 if (Current.is(tok::question))
647 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper24849712013-03-01 16:48:32 +0000648 if ((Current.is(tok::period) || Current.is(tok::arrow)) &&
649 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
650 State.Stack.back().StartOfFunctionCall =
651 Current.LastInChainOfCalls ? 0 : State.Column;
Daniel Jasper7d812812013-02-21 15:00:29 +0000652 if (Current.Type == TT_CtorInitializerColon) {
653 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
654 State.Stack.back().AvoidBinPacking = true;
655 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000656 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000657
Daniel Jasper29f123b2013-02-08 15:28:42 +0000658 // Insert scopes created by fake parenthesis.
659 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
660 ParenState NewParenState = State.Stack.back();
661 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
Daniel Jasper237d4c12013-02-23 21:01:55 +0000662 NewParenState.BreakBeforeParameter = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000663 State.Stack.push_back(NewParenState);
664 }
665
Daniel Jaspercf225b62012-12-24 13:43:52 +0000666 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000667 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000668 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
669 Current.is(tok::l_brace) ||
670 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000671 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000672 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000673 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000674 NewIndent = 2 + State.Stack.back().LastSpace;
675 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000676 } else {
Daniel Jasper24849712013-03-01 16:48:32 +0000677 NewIndent = 4 + std::max(State.Stack.back().LastSpace,
678 State.Stack.back().StartOfFunctionCall);
Daniel Jasper3a39ac72013-02-28 09:39:12 +0000679 AvoidBinPacking =
680 !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000681 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000682 State.Stack.push_back(
683 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
684 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000685 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000686 }
687
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000688 // If this '[' opens an ObjC call, determine whether all parameters fit into
689 // one line and put one per line if they don't.
690 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
691 Current.MatchingParen != NULL) {
692 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
693 State.Stack.back().BreakBeforeParameter = true;
694 }
695
Daniel Jaspercf225b62012-12-24 13:43:52 +0000696 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000697 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000698 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
699 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
700 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000701 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000702 --State.ParenLevel;
703 }
704
705 // Remove scopes created by fake parenthesis.
706 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
707 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000708 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000709
Manuel Klimeke9a62262013-02-20 15:32:58 +0000710 if (Current.is(tok::string_literal)) {
Manuel Klimekb56b6d12013-02-20 15:25:48 +0000711 State.StartOfStringLiteral = State.Column;
712 } else if (Current.isNot(tok::comment)) {
713 State.StartOfStringLiteral = 0;
714 }
715
Manuel Klimek8092a942013-02-20 10:15:13 +0000716 State.Column += Current.FormatTok.TokenLength;
717
Daniel Jasper26f7e782013-01-08 14:56:18 +0000718 if (State.NextToken->Children.empty())
719 State.NextToken = NULL;
720 else
721 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000722
Manuel Klimek8092a942013-02-20 10:15:13 +0000723 return breakProtrudingToken(Current, State, DryRun);
724 }
725
726 /// \brief If the current token sticks out over the end of the line, break
727 /// it if possible.
728 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
729 bool DryRun) {
730 if (Current.isNot(tok::string_literal))
731 return 0;
732
733 unsigned Penalty = 0;
734 unsigned TailOffset = 0;
735 unsigned TailLength = Current.FormatTok.TokenLength;
736 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
737 unsigned OffsetFromStart = 0;
738 while (StartColumn + TailLength > getColumnLimit()) {
739 StringRef Text = StringRef(Current.FormatTok.Tok.getLiteralData() +
740 TailOffset, TailLength);
Manuel Klimekbc30c712013-03-01 13:29:19 +0000741 if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000742 break;
Manuel Klimekbc30c712013-03-01 13:29:19 +0000743 StringRef::size_type SplitPoint = getSplitPoint(
744 Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
Manuel Klimek8092a942013-02-20 10:15:13 +0000745 if (SplitPoint == StringRef::npos)
746 break;
747 assert(SplitPoint != 0);
748 // +2, because 'Text' starts after the opening quotes, and does not
749 // include the closing quote we need to insert.
750 unsigned WhitespaceStartColumn =
751 StartColumn + OffsetFromStart + SplitPoint + 2;
752 State.Stack.back().LastSpace = StartColumn;
753 if (!DryRun) {
754 Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"",
755 Line.InPPDirective, StartColumn,
756 WhitespaceStartColumn, Style);
757 }
758 TailOffset += SplitPoint + 1;
759 TailLength -= SplitPoint + 1;
760 OffsetFromStart = 1;
Daniel Jasper0fb382b2013-02-26 12:52:34 +0000761 Penalty += Style.PenaltyExcessCharacter;
Daniel Jasperfaab0d32013-02-27 09:47:53 +0000762 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
763 State.Stack[i].BreakBeforeParameter = true;
Manuel Klimek8092a942013-02-20 10:15:13 +0000764 }
765 State.Column = StartColumn + TailLength;
766 return Penalty;
767 }
768
769 StringRef::size_type
770 getSplitPoint(StringRef Text, StringRef::size_type Offset) {
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000771 StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +0000772 if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +0000773 return SpaceOffset;
774 StringRef::size_type SlashOffset = Text.rfind('/', Offset);
Manuel Klimek00905912013-03-04 20:03:38 +0000775 if (SlashOffset != StringRef::npos && SlashOffset != 0)
Manuel Klimekbc30c712013-03-01 13:29:19 +0000776 return SlashOffset;
777 if (Offset > 1)
778 // Do not split at 0.
Manuel Klimekaf31fd72013-03-01 13:14:08 +0000779 return Offset - 1;
Manuel Klimekbc30c712013-03-01 13:29:19 +0000780 return StringRef::npos;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000781 }
782
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000783 unsigned getColumnLimit() {
Daniel Jaspera4d46212013-02-28 11:05:57 +0000784 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000785 }
786
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000787 /// \brief An edge in the solution space from \c Previous->State to \c State,
788 /// inserting a newline dependent on the \c NewLine.
789 struct StateNode {
790 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
Daniel Jasperf11a7052013-02-21 21:33:55 +0000791 : State(State), NewLine(NewLine), Previous(Previous) {}
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000792 LineState State;
793 bool NewLine;
794 StateNode *Previous;
795 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000796
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000797 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
798 ///
799 /// In case of equal penalties, we want to prefer states that were inserted
800 /// first. During state generation we make sure that we insert states first
801 /// that break the line as late as possible.
802 typedef std::pair<unsigned, unsigned> OrderedPenalty;
803
804 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
805 /// \c State has the given \c OrderedPenalty.
806 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
807
808 /// \brief The BFS queue type.
809 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
810 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000811
812 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000813 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000814 /// This implements a variant of Dijkstra's algorithm on the graph that spans
815 /// the solution space (\c LineStates are the nodes). The algorithm tries to
816 /// find the shortest path (the one with lowest penalty) from \p InitialState
817 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000818 unsigned analyzeSolutionSpace(LineState &InitialState) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000819 std::set<LineState> Seen;
820
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000821 // Insert start element into queue.
Daniel Jasperfc759082013-02-14 14:26:07 +0000822 StateNode *Node =
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000823 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
824 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
825 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000826
827 // While not empty, take first element and follow edges.
828 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000829 unsigned Penalty = Queue.top().first.first;
Daniel Jasperfc759082013-02-14 14:26:07 +0000830 StateNode *Node = Queue.top().second;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000831 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000832 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000833 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000834 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000835 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000836
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000837 if (!Seen.insert(Node->State).second)
838 // State already examined with lower penalty.
839 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000840
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000841 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
842 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000843 }
844
845 if (Queue.empty())
846 // We were unable to find a solution, do nothing.
847 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000848 return 0;
849
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000850 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000851 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000852 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000853
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000854 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000855 return Queue.top().second->State.Column;
856 }
857
858 void reconstructPath(LineState &State, StateNode *Current) {
859 // FIXME: This recursive implementation limits the possible number
860 // of tokens per line if compiled into a binary with small stack space.
861 // To become more independent of stack frame limitations we would need
862 // to also change the TokenAnnotator.
863 if (Current->Previous == NULL)
864 return;
865 reconstructPath(State, Current->Previous);
866 DEBUG({
867 if (Current->NewLine) {
Daniel Jaspera03ab102013-02-13 20:33:44 +0000868 llvm::errs()
869 << "Penalty for splitting before "
870 << Current->Previous->State.NextToken->FormatTok.Tok.getName()
871 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000872 }
873 });
874 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000875 }
876
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000877 /// \brief Add the following state to the analysis queue \c Queue.
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000878 ///
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000879 /// Assume the current state is \p PreviousNode and has been reached with a
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000880 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000881 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
882 bool NewLine) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000883 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000884 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000885 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000886 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000887 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000888 Penalty += PreviousNode->State.NextToken->SplitPenalty;
889
890 StateNode *Node = new (Allocator.Allocate())
891 StateNode(PreviousNode->State, NewLine, PreviousNode);
Manuel Klimek8092a942013-02-20 10:15:13 +0000892 Penalty += addTokenToState(NewLine, true, Node->State);
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000893 if (Node->State.Column > getColumnLimit()) {
894 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000895 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000896 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000897
898 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
899 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000900 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000901
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000902 /// \brief Returns \c true, if a line break after \p State is allowed.
903 bool canBreak(const LineState &State) {
904 if (!State.NextToken->CanBreakBefore &&
905 !(State.NextToken->is(tok::r_brace) &&
906 State.Stack.back().BreakBeforeClosingBrace))
907 return false;
Daniel Jaspercf5767d2013-02-18 11:05:07 +0000908 // This prevents breaks like:
909 // ...
910 // SomeParameter, OtherParameter).DoSomething(
911 // ...
912 // As they hide "DoSomething" and generally bad for readability.
913 if (State.NextToken->Parent->is(tok::l_paren) &&
914 State.ParenLevel <= State.StartOfLineLevel)
915 return false;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000916 // Trying to insert a parameter on a new line if there are already more than
917 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000918 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000919 State.Stack.back().AvoidBinPacking)
920 return false;
921 return true;
922 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000923
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000924 /// \brief Returns \c true, if a line break after \p State is mandatory.
925 bool mustBreak(const LineState &State) {
926 if (State.NextToken->MustBreakBefore)
927 return true;
928 if (State.NextToken->is(tok::r_brace) &&
929 State.Stack.back().BreakBeforeClosingBrace)
930 return true;
931 if (State.NextToken->Parent->is(tok::semi) &&
932 State.LineContainsContinuedForLoopSection)
933 return true;
Daniel Jasper237d4c12013-02-23 21:01:55 +0000934 if ((State.NextToken->Parent->is(tok::comma) ||
935 State.NextToken->Parent->is(tok::semi) ||
936 State.NextToken->is(tok::question) ||
937 State.NextToken->Type == TT_ConditionalExpr) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000938 State.Stack.back().BreakBeforeParameter &&
Daniel Jasperc5cfa492013-02-14 09:19:04 +0000939 !isTrailingComment(*State.NextToken) &&
Daniel Jasper7d812812013-02-21 15:00:29 +0000940 State.NextToken->isNot(tok::r_paren) &&
941 State.NextToken->isNot(tok::r_brace))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000942 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000943 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
944 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000945 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000946 State.NextToken->LongestObjCSelectorName == 0 &&
947 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000948 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000949 if ((State.NextToken->Type == TT_CtorInitializerColon ||
950 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000951 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000952 return true;
953 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000954 }
955
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 FormatStyle Style;
957 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000958 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000959 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000960 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000961 WhitespaceManager &Whitespaces;
Manuel Klimek62a48fb2013-02-13 10:54:19 +0000962
963 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
964 QueueType Queue;
965 // Increasing count of \c StateNode items we have created. This is used
966 // to create a deterministic order independent of the container.
967 unsigned Count;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000968};
969
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000970class LexerBasedFormatTokenSource : public FormatTokenSource {
971public:
972 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000973 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000974 IdentTable(Lex.getLangOpts()) {
975 Lex.SetKeepWhitespaceMode(true);
976 }
977
978 virtual FormatToken getNextToken() {
979 if (GreaterStashed) {
980 FormatTok.NewlinesBefore = 0;
981 FormatTok.WhiteSpaceStart =
982 FormatTok.Tok.getLocation().getLocWithOffset(1);
983 FormatTok.WhiteSpaceLength = 0;
984 GreaterStashed = false;
985 return FormatTok;
986 }
987
988 FormatTok = FormatToken();
989 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000990 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000991 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000992 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
993 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000994
995 // Consume and record whitespace until we find a significant token.
996 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000997 unsigned Newlines = Text.count('\n');
Daniel Jasper1eee6c42013-03-04 13:43:19 +0000998 if (Newlines > 0)
999 FormatTok.LastNewlineOffset =
1000 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
Manuel Klimeka28fc062013-02-11 12:33:24 +00001001 unsigned EscapedNewlines = Text.count("\\\n");
1002 FormatTok.NewlinesBefore += Newlines;
1003 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001004 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1005
1006 if (FormatTok.Tok.is(tok::eof))
1007 return FormatTok;
1008 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001009 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001010 }
Manuel Klimek95419382013-01-07 07:56:50 +00001011
1012 // Now FormatTok is the next non-whitespace token.
1013 FormatTok.TokenLength = Text.size();
1014
Manuel Klimekd4397b92013-01-04 23:34:14 +00001015 // In case the token starts with escaped newlines, we want to
1016 // take them into account as whitespace - this pattern is quite frequent
1017 // in macro definitions.
1018 // FIXME: What do we want to do with other escaped spaces, and escaped
1019 // spaces or newlines in the middle of tokens?
1020 // FIXME: Add a more explicit test.
1021 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001022 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001023 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001024 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001025 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001026 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001027 }
1028
1029 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001030 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001031 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001032 FormatTok.Tok.setKind(Info.getTokenID());
1033 }
1034
1035 if (FormatTok.Tok.is(tok::greatergreater)) {
1036 FormatTok.Tok.setKind(tok::greater);
Daniel Jasperb6f02f32013-02-28 10:06:05 +00001037 FormatTok.TokenLength = 1;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001038 GreaterStashed = true;
1039 }
1040
Daniel Jasper812c0452013-03-01 16:45:59 +00001041 // If we reformat comments, we remove trailing whitespace. Update the length
1042 // accordingly.
1043 if (FormatTok.Tok.is(tok::comment))
1044 FormatTok.TokenLength = Text.rtrim().size();
1045
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001046 return FormatTok;
1047 }
1048
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001049 IdentifierTable &getIdentTable() { return IdentTable; }
1050
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001051private:
1052 FormatToken FormatTok;
1053 bool GreaterStashed;
1054 Lexer &Lex;
1055 SourceManager &SourceMgr;
1056 IdentifierTable IdentTable;
1057
1058 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001059 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001060 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1061 Tok.getLength());
1062 }
1063};
1064
Daniel Jasperbac016b2012-12-03 18:12:45 +00001065class Formatter : public UnwrappedLineConsumer {
1066public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001067 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1068 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001069 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001070 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperf11a7052013-02-21 21:33:55 +00001071 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001072
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001073 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001074
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001075 void deriveLocalStyle() {
1076 unsigned CountBoundToVariable = 0;
1077 unsigned CountBoundToType = 0;
1078 bool HasCpp03IncompatibleFormat = false;
1079 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1080 if (AnnotatedLines[i].First.Children.empty())
1081 continue;
1082 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
1083 while (!Tok->Children.empty()) {
1084 if (Tok->Type == TT_PointerOrReference) {
1085 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
1086 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
1087 if (SpacesBefore && !SpacesAfter)
1088 ++CountBoundToVariable;
1089 else if (!SpacesBefore && SpacesAfter)
1090 ++CountBoundToType;
1091 }
1092
Daniel Jasper29f123b2013-02-08 15:28:42 +00001093 if (Tok->Type == TT_TemplateCloser &&
1094 Tok->Parent->Type == TT_TemplateCloser &&
1095 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001096 HasCpp03IncompatibleFormat = true;
1097 Tok = &Tok->Children[0];
1098 }
1099 }
1100 if (Style.DerivePointerBinding) {
1101 if (CountBoundToType > CountBoundToVariable)
1102 Style.PointerBindsToType = true;
1103 else if (CountBoundToType < CountBoundToVariable)
1104 Style.PointerBindsToType = false;
1105 }
1106 if (Style.Standard == FormatStyle::LS_Auto) {
1107 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
1108 : FormatStyle::LS_Cpp03;
1109 }
1110 }
1111
Daniel Jasperbac016b2012-12-03 18:12:45 +00001112 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001113 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001114 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001115 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001116 unsigned PreviousEndOfLineColumn = 0;
Nico Weberc2e6d2a2013-02-11 15:32:15 +00001117 TokenAnnotator Annotator(Style, SourceMgr, Lex,
1118 Tokens.getIdentTable().get("in"));
Daniel Jasper995e8202013-01-14 13:08:07 +00001119 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +00001120 Annotator.annotate(AnnotatedLines[i]);
1121 }
1122 deriveLocalStyle();
1123 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1124 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +00001125 }
Manuel Klimek547d5db2013-02-08 17:38:27 +00001126 std::vector<int> IndentForLevel;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001127 bool PreviousLineWasTouched = false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001128 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1129 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001130 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001131 const AnnotatedLine &TheLine = *I;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001132 int Offset = getIndentOffset(TheLine.First);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001133 while (IndentForLevel.size() <= TheLine.Level)
1134 IndentForLevel.push_back(-1);
1135 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper29333162013-02-18 13:08:03 +00001136 bool WasMoved =
1137 PreviousLineWasTouched && TheLine.First.FormatTok.NewlinesBefore == 0;
Daniel Jasper516fb312013-03-01 18:11:39 +00001138 if (TheLine.First.is(tok::eof)) {
1139 if (PreviousLineWasTouched) {
1140 unsigned NewLines =
1141 std::min(TheLine.First.FormatTok.NewlinesBefore, 1u);
1142 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
1143 /*WhitespaceStartColumn*/ 0, Style);
1144 }
1145 } else if (TheLine.Type != LT_Invalid &&
Daniel Jasperf3023542013-03-07 20:50:00 +00001146 (WasMoved || touchesLine(TheLine))) {
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001147 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001148 unsigned Indent = LevelIndent;
1149 if (static_cast<int>(Indent) + Offset >= 0)
1150 Indent += Offset;
1151 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
1152 StructuralError) {
1153 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
1154 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1155 } else {
1156 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1157 PreviousEndOfLineColumn);
1158 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001159 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001160 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001161 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001162 StructuralError);
Daniel Jaspera4d46212013-02-28 11:05:57 +00001163 PreviousEndOfLineColumn =
1164 Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
Manuel Klimek547d5db2013-02-08 17:38:27 +00001165 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001166 PreviousLineWasTouched = true;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001167 } else {
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001168 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
1169 TheLine.First.FormatTok.IsFirst) {
1170 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1171 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1172 unsigned LevelIndent = Indent;
1173 if (static_cast<int>(LevelIndent) - Offset >= 0)
1174 LevelIndent -= Offset;
1175 IndentForLevel[TheLine.Level] = LevelIndent;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001176
1177 // Remove trailing whitespace of the previous line if it was touched.
Daniel Jasperf3023542013-03-07 20:50:00 +00001178 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001179 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
1180 PreviousEndOfLineColumn);
Daniel Jasper9ece2bb2013-02-12 16:51:23 +00001181 }
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001182 // If we did not reformat this unwrapped line, the column at the end of
1183 // the last token is unchanged - thus, we can calculate the end of the
1184 // last token.
1185 PreviousEndOfLineColumn =
1186 SourceMgr.getSpellingColumnNumber(
1187 TheLine.Last->FormatTok.Tok.getLocation()) +
1188 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1189 SourceMgr, Lex.getLangOpts()) - 1;
1190 PreviousLineWasTouched = false;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001191 }
1192 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001193 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001194 }
1195
1196private:
Manuel Klimek547d5db2013-02-08 17:38:27 +00001197 /// \brief Get the indent of \p Level from \p IndentForLevel.
1198 ///
1199 /// \p IndentForLevel must contain the indent for the level \c l
1200 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1201 /// that level is unknown.
Daniel Jasperfc759082013-02-14 14:26:07 +00001202 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001203 if (IndentForLevel[Level] != -1)
1204 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001205 if (Level == 0)
1206 return 0;
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001207 return getIndent(IndentForLevel, Level - 1) + 2;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001208 }
1209
1210 /// \brief Get the offset of the line relatively to the level.
1211 ///
1212 /// For example, 'public:' labels in classes are offset by 1 or 2
1213 /// characters to the left from their level.
Daniel Jasperc78c6b32013-02-14 09:58:41 +00001214 int getIndentOffset(const AnnotatedToken &RootToken) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001215 bool IsAccessModifier = false;
1216 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1217 RootToken.is(tok::kw_private))
1218 IsAccessModifier = true;
1219 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1220 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1221 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1222 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1223 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1224 IsAccessModifier = true;
1225
1226 if (IsAccessModifier)
1227 return Style.AccessModifierOffset;
1228 return 0;
1229 }
1230
Manuel Klimek517e8942013-01-11 17:54:10 +00001231 /// \brief Tries to merge lines into one.
1232 ///
1233 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1234 /// if possible; note that \c I will be incremented when lines are merged.
1235 ///
1236 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001237 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001238 std::vector<AnnotatedLine>::iterator &I,
1239 std::vector<AnnotatedLine>::iterator E) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001240 // We can never merge stuff if there are trailing line comments.
1241 if (I->Last->Type == TT_LineComment)
1242 return;
1243
Daniel Jaspera4d46212013-02-28 11:05:57 +00001244 unsigned Limit = Style.ColumnLimit - Indent;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001245 // If we already exceed the column limit, we set 'Limit' to 0. The different
1246 // tryMerge..() functions can then decide whether to still do merging.
1247 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001248
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001249 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001250 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001251
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001252 if (I->Last->is(tok::l_brace)) {
1253 tryMergeSimpleBlock(I, E, Limit);
1254 } else if (I->First.is(tok::kw_if)) {
1255 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001256 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1257 I->First.FormatTok.IsFirst)) {
1258 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001259 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001260 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001261 }
1262
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001263 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1264 std::vector<AnnotatedLine>::iterator E,
1265 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001266 if (Limit == 0)
1267 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001268 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001269 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1270 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001271 if (I + 2 != E && (I + 2)->InPPDirective &&
1272 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1273 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001274 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001275 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001276 join(Line, *(++I));
1277 }
1278
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001279 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1280 std::vector<AnnotatedLine>::iterator E,
1281 unsigned Limit) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001282 if (Limit == 0)
1283 return;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001284 if (!Style.AllowShortIfStatementsOnASingleLine)
1285 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001286 if ((I + 1)->InPPDirective != I->InPPDirective ||
1287 ((I + 1)->InPPDirective &&
1288 (I + 1)->First.FormatTok.HasUnescapedNewline))
1289 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001290 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001291 if (Line.Last->isNot(tok::r_paren))
1292 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001293 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001294 return;
1295 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1296 return;
1297 // Only inline simple if's (no nested if or else).
1298 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1299 return;
1300 join(Line, *(++I));
1301 }
1302
1303 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001304 std::vector<AnnotatedLine>::iterator E,
1305 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001306 // First, check that the current line allows merging. This is the case if
1307 // we're not in a control flow statement and the last token is an opening
1308 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001309 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001310 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001311 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1312 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1313 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1314 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001315 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001316 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1317 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001318 if (!AllowedTokens)
1319 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001320
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001321 AnnotatedToken *Tok = &(I + 1)->First;
1322 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
Daniel Jasperf11a7052013-02-21 21:33:55 +00001323 !Tok->MustBreakBefore) {
1324 // We merge empty blocks even if the line exceeds the column limit.
Daniel Jasper729a7432013-02-11 12:36:37 +00001325 Tok->SpacesRequiredBefore = 0;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001326 Tok->CanBreakBefore = true;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001327 join(Line, *(I + 1));
1328 I += 1;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001329 } else if (Limit != 0) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001330 // Check that we still have three lines and they fit into the limit.
1331 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1332 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001333 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001334
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001335 // Second, check that the next line does not contain any braces - if it
1336 // does, readability declines when putting it into a single line.
1337 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1338 return;
1339 do {
1340 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1341 return;
1342 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1343 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001344
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001345 // Last, check that the third line contains a single closing brace.
1346 Tok = &(I + 2)->First;
1347 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1348 Tok->MustBreakBefore)
1349 return;
1350
1351 join(Line, *(I + 1));
1352 join(Line, *(I + 2));
1353 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001354 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001355 }
1356
1357 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1358 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001359 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1360 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001361 }
1362
Daniel Jasper995e8202013-01-14 13:08:07 +00001363 void join(AnnotatedLine &A, const AnnotatedLine &B) {
Daniel Jasperf11a7052013-02-21 21:33:55 +00001364 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
Daniel Jasper995e8202013-01-14 13:08:07 +00001365 A.Last->Children.push_back(B.First);
1366 while (!A.Last->Children.empty()) {
1367 A.Last->Children[0].Parent = A.Last;
Daniel Jasperf11a7052013-02-21 21:33:55 +00001368 A.Last->Children[0].TotalLength += LengthA;
Daniel Jasper995e8202013-01-14 13:08:07 +00001369 A.Last = &A.Last->Children[0];
1370 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001371 }
1372
Daniel Jasperf3023542013-03-07 20:50:00 +00001373 bool touchesRanges(const CharSourceRange& Range) {
1374 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1375 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
1376 Ranges[i].getBegin()) &&
1377 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1378 Range.getBegin()))
1379 return true;
1380 }
1381 return false;
1382 }
1383
1384 bool touchesLine(const AnnotatedLine &TheLine) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001385 const FormatToken *First = &TheLine.First.FormatTok;
1386 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001387 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1eee6c42013-03-04 13:43:19 +00001388 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
1389 Last->Tok.getLocation());
Daniel Jasperf3023542013-03-07 20:50:00 +00001390 return touchesRanges(LineRange);
1391 }
1392
1393 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
1394 const FormatToken *First = &TheLine.First.FormatTok;
1395 CharSourceRange LineRange = CharSourceRange::getCharRange(
1396 First->WhiteSpaceStart,
1397 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
1398 return touchesRanges(LineRange);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001399 }
1400
1401 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001402 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001403 }
1404
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001405 /// \brief Add a new line and the required indent before the first Token
1406 /// of the \c UnwrappedLine if there was no structural parsing error.
1407 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek547d5db2013-02-08 17:38:27 +00001408 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1409 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001410 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001411
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001412 unsigned Newlines =
1413 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001414 if (Newlines == 0 && !Tok.IsFirst)
1415 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001416
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001417 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001418 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001419 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001420 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1421 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001422 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001423 }
1424
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001425 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001426 FormatStyle Style;
1427 Lexer &Lex;
1428 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001429 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001430 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001431 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001432 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001433};
1434
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001435tooling::Replacements
1436reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1437 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001438 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001439 OwningPtr<DiagnosticConsumer> DiagPrinter;
1440 if (DiagClient == 0) {
1441 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1442 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1443 DiagClient = DiagPrinter.get();
1444 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001445 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001446 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001447 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001448 Diagnostics.setSourceManager(&SourceMgr);
1449 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001450 return formatter.format();
1451}
1452
Daniel Jasper46ef8522013-01-10 13:08:12 +00001453LangOptions getFormattingLangOpts() {
1454 LangOptions LangOpts;
1455 LangOpts.CPlusPlus = 1;
1456 LangOpts.CPlusPlus11 = 1;
1457 LangOpts.Bool = 1;
1458 LangOpts.ObjC1 = 1;
1459 LangOpts.ObjC2 = 1;
1460 return LangOpts;
1461}
1462
Daniel Jaspercd162382013-01-07 13:26:07 +00001463} // namespace format
1464} // namespace clang