blob: bef5f9284397fc60ac82bd2fcb4f6dd3f9a1b456 [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 Klimekca547db2013-01-16 14:55:28 +000026#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000027#include <string>
28
Manuel Klimekca547db2013-01-16 14:55:28 +000029// Uncomment to get debug output from tests:
30// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
31
Daniel Jasperbac016b2012-12-03 18:12:45 +000032namespace clang {
33namespace format {
34
Daniel Jasperbac016b2012-12-03 18:12:45 +000035FormatStyle getLLVMStyle() {
36 FormatStyle LLVMStyle;
37 LLVMStyle.ColumnLimit = 80;
38 LLVMStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000039 LLVMStyle.PointerBindsToType = false;
40 LLVMStyle.DerivePointerBinding = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000041 LLVMStyle.AccessModifierOffset = -2;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000042 LLVMStyle.Standard = FormatStyle::LS_Cpp03;
Alexander Kornienko15757312012-12-06 18:03:27 +000043 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000044 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000045 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +000046 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000047 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000048 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000049 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000050 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000051 LLVMStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +000052 return LLVMStyle;
53}
54
55FormatStyle getGoogleStyle() {
56 FormatStyle GoogleStyle;
57 GoogleStyle.ColumnLimit = 80;
58 GoogleStyle.MaxEmptyLinesToKeep = 1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000059 GoogleStyle.PointerBindsToType = true;
60 GoogleStyle.DerivePointerBinding = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000061 GoogleStyle.AccessModifierOffset = -1;
Daniel Jasper8ff690a2013-02-06 14:22:40 +000062 GoogleStyle.Standard = FormatStyle::LS_Auto;
Alexander Kornienko15757312012-12-06 18:03:27 +000063 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000064 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +000065 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +000066 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000067 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000068 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000069 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000070 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000071 GoogleStyle.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +000072 return GoogleStyle;
73}
74
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000075FormatStyle getChromiumStyle() {
76 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +000077 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = 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 Jasper15417ef2013-02-06 20:07:35 +0000119 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000120 if (Style.ColumnLimit >=
121 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
122 Comments.push_back(StoredComment());
123 Comments.back().Tok = Tok.FormatTok;
124 Comments.back().Spaces = Spaces;
125 Comments.back().NewLines = NewLines;
Daniel Jasper474e4622013-02-06 22:04:05 +0000126 if (NewLines == 0)
127 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
128 else
129 Comments.back().MinColumn = Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000130 Comments.back().MaxColumn =
131 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000132 return;
133 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000134 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000135
136 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000137 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000138 alignComments();
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000139 storeReplacement(Tok.FormatTok,
140 std::string(NewLines, '\n') + std::string(Spaces, ' '));
141 }
142
143 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
144 /// backslashes to escape newlines inside a preprocessor directive.
145 ///
146 /// This function and \c replaceWhitespace have the same behavior if
147 /// \c Newlines == 0.
148 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
149 unsigned Spaces, unsigned WhitespaceStartColumn,
150 const FormatStyle &Style) {
151 std::string NewLineText;
152 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000153 unsigned Offset =
154 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000155 for (unsigned i = 0; i < NewLines; ++i) {
156 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
157 NewLineText += "\\\n";
158 Offset = 0;
159 }
160 }
161 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
162 }
163
164 /// \brief Returns all the \c Replacements created during formatting.
165 const tooling::Replacements &generateReplacements() {
166 alignComments();
167 return Replaces;
168 }
169
170private:
171 /// \brief Structure to store a comment for later layout and alignment.
172 struct StoredComment {
173 FormatToken Tok;
174 unsigned MinColumn;
175 unsigned MaxColumn;
176 unsigned NewLines;
177 unsigned Spaces;
178 };
179 SmallVector<StoredComment, 16> Comments;
180 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
181
182 /// \brief Try to align all stashed comments.
183 void alignComments() {
184 unsigned MinColumn = 0;
185 unsigned MaxColumn = UINT_MAX;
186 comment_iterator Start = Comments.begin();
187 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
188 ++I) {
189 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
190 alignComments(Start, I, MinColumn);
191 MinColumn = I->MinColumn;
192 MaxColumn = I->MaxColumn;
193 Start = I;
194 } else {
195 MinColumn = std::max(MinColumn, I->MinColumn);
196 MaxColumn = std::min(MaxColumn, I->MaxColumn);
197 }
198 }
199 alignComments(Start, Comments.end(), MinColumn);
200 Comments.clear();
201 }
202
203 /// \brief Put all the comments between \p I and \p E into \p Column.
204 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
205 while (I != E) {
206 unsigned Spaces = I->Spaces + Column - I->MinColumn;
207 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper29f123b2013-02-08 15:28:42 +0000208 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000209 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000210 }
211 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000212
213 /// \brief Stores \p Text as the replacement for the whitespace in front of
214 /// \p Tok.
215 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000216 // Don't create a replacement, if it does not change anything.
217 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
218 Tok.WhiteSpaceLength) == Text)
219 return;
220
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000221 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
222 Tok.WhiteSpaceLength, Text));
223 }
224
225 SourceManager &SourceMgr;
226 tooling::Replacements Replaces;
227};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000228
Daniel Jasperbac016b2012-12-03 18:12:45 +0000229class UnwrappedLineFormatter {
230public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000231 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000232 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000233 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000234 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000235 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000236 FirstIndent(FirstIndent), RootToken(RootToken),
237 Whitespaces(Whitespaces) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000238 }
239
Manuel Klimekd4397b92013-01-04 23:34:14 +0000240 /// \brief Formats an \c UnwrappedLine.
241 ///
242 /// \returns The column after the last token in the last line of the
243 /// \c UnwrappedLine.
244 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000245 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000246 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000247 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000248 State.NextToken = &RootToken;
Daniel Jasperd399bff2013-02-05 09:41:21 +0000249 State.Stack.push_back(
250 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
251 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000252 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000253 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000254 State.ParenLevel = 0;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000255
Manuel Klimekca547db2013-01-16 14:55:28 +0000256 DEBUG({
257 DebugTokenState(*State.NextToken);
258 });
259
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000260 // The first token has already been indented and thus consumed.
261 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000262
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000263 // If everything fits on a single line, just put it there.
264 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
265 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000266 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000267 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000268 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000270
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000271 // If the ObjC method declaration does not fit on a line, we should format
272 // it with one arg per line.
273 if (Line.Type == LT_ObjCMethodDecl)
274 State.Stack.back().BreakBeforeParameter = true;
275
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000276 // Find best solution in solution space.
277 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000278 }
279
280private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000281 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
282 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000283 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
284 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000285 llvm::errs();
286 }
287
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000288 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000289 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
290 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000291 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
292 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000293 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000294 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000295 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000296
Daniel Jasperbac016b2012-12-03 18:12:45 +0000297 /// \brief The position to which a specific parenthesis level needs to be
298 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000299 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000300
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000301 /// \brief The position of the last space on each level.
302 ///
303 /// Used e.g. to break like:
304 /// functionCall(Parameter, otherCall(
305 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000306 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000308 /// \brief The position the first "<<" operator encountered on each level.
309 ///
310 /// Used to align "<<" operators. 0 if no such operator has been encountered
311 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000312 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000313
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000314 /// \brief Whether a newline needs to be inserted before the block's closing
315 /// brace.
316 ///
317 /// We only want to insert a newline before the closing brace if there also
318 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000319 bool BreakBeforeClosingBrace;
320
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000321 /// \brief The column of a \c ? in a conditional expression;
322 unsigned QuestionColumn;
323
Daniel Jasperf343cab2013-01-31 14:59:26 +0000324 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
325 /// lines, in this context.
326 bool AvoidBinPacking;
327
328 /// \brief Break after the next comma (or all the commas in this context if
329 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000330 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000331
332 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000333 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000334
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000335 /// \brief The position of the colon in an ObjC method declaration/call.
336 unsigned ColonPos;
337
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000338 bool operator<(const ParenState &Other) const {
339 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000340 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000341 if (LastSpace != Other.LastSpace)
342 return LastSpace < Other.LastSpace;
343 if (FirstLessLess != Other.FirstLessLess)
344 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000345 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
346 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000347 if (QuestionColumn != Other.QuestionColumn)
348 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000349 if (AvoidBinPacking != Other.AvoidBinPacking)
350 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000351 if (BreakBeforeParameter != Other.BreakBeforeParameter)
352 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000353 if (HasMultiParameterLine != Other.HasMultiParameterLine)
354 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000355 if (ColonPos != Other.ColonPos)
356 return ColonPos < Other.ColonPos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000357 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000358 }
359 };
360
361 /// \brief The current state when indenting a unwrapped line.
362 ///
363 /// As the indenting tries different combinations this is copied by value.
364 struct LineState {
365 /// \brief The number of used columns in the current line.
366 unsigned Column;
367
368 /// \brief The token that needs to be next formatted.
369 const AnnotatedToken *NextToken;
370
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000371 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000372 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000373 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000374 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000375
376 /// \brief \c true if this line contains a continued for-loop section.
377 bool LineContainsContinuedForLoopSection;
378
Daniel Jasper29f123b2013-02-08 15:28:42 +0000379 /// \brief The level of nesting inside (), [], <> and {}.
380 unsigned ParenLevel;
381
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000382 /// \brief A stack keeping track of properties applying to parenthesis
383 /// levels.
384 std::vector<ParenState> Stack;
385
386 /// \brief Comparison operator to be able to used \c LineState in \c map.
387 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000388 if (Other.NextToken != NextToken)
389 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390 if (Other.Column != Column)
391 return Other.Column > Column;
Daniel Jasper2e603772013-01-29 11:21:01 +0000392 if (Other.VariablePos != VariablePos)
393 return Other.VariablePos < VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000394 if (Other.LineContainsContinuedForLoopSection !=
395 LineContainsContinuedForLoopSection)
396 return LineContainsContinuedForLoopSection;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000397 if (Other.ParenLevel != ParenLevel)
398 return Other.ParenLevel < ParenLevel;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000399 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000400 }
401 };
402
Daniel Jasper20409152012-12-04 14:54:30 +0000403 /// \brief Appends the next token to \p State and updates information
404 /// necessary for indentation.
405 ///
406 /// Puts the token on the current line if \p Newline is \c true and adds a
407 /// line break and necessary indentation otherwise.
408 ///
409 /// If \p DryRun is \c false, also creates and stores the required
410 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000411 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000412 const AnnotatedToken &Current = *State.NextToken;
413 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000414 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000415
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000416 if (Current.Type == TT_ImplicitStringLiteral) {
417 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
418 State.NextToken->FormatTok.TokenLength;
419 if (State.NextToken->Children.empty())
420 State.NextToken = NULL;
421 else
422 State.NextToken = &State.NextToken->Children[0];
423 return;
424 }
425
Daniel Jasperbac016b2012-12-03 18:12:45 +0000426 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000427 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000428 if (Current.is(tok::r_brace)) {
429 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000430 } else if (Current.is(tok::string_literal) &&
431 Previous.is(tok::string_literal)) {
432 State.Column = State.Column - Previous.FormatTok.TokenLength;
433 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000434 State.Stack.back().FirstLessLess != 0) {
435 State.Column = State.Stack.back().FirstLessLess;
436 } else if (State.ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000437 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000438 Current.is(tok::period) || Current.is(tok::arrow) ||
439 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000440 // Indent and extra 4 spaces after if we know the current expression is
441 // continued. Don't do that on the top level, as we already indent 4
442 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000443 State.Column = std::max(State.Stack.back().LastSpace,
444 State.Stack.back().Indent) + 4;
445 } else if (Current.Type == TT_ConditionalExpr) {
446 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000447 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000448 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
449 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000450 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000451 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
452 Current.Type == TT_StartOfName) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000453 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000454 } else if (Current.Type == TT_ObjCSelectorName) {
455 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
456 State.Column =
457 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
458 } else {
459 State.Column = State.Stack.back().Indent;
460 State.Stack.back().ColonPos =
461 State.Column + Current.FormatTok.TokenLength;
462 }
463 } else if (Previous.Type == TT_ObjCMethodExpr) {
464 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000465 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000466 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000467 }
468
Daniel Jasperf343cab2013-01-31 14:59:26 +0000469 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000470 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000471
Daniel Jasper26f7e782013-01-08 14:56:18 +0000472 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000473 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000474
Manuel Klimek060143e2013-01-02 18:33:23 +0000475 if (!DryRun) {
476 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000477 Whitespaces.replaceWhitespace(Current, 1, State.Column,
478 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000479 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000480 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
481 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000482 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000483
Daniel Jasper29f123b2013-02-08 15:28:42 +0000484 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000485 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000486 State.Stack.back().Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000487 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000488 if (Current.is(tok::equal) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000489 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000490 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000491
Daniel Jasper26f7e782013-01-08 14:56:18 +0000492 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
493 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000494 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000495
Daniel Jasperbac016b2012-12-03 18:12:45 +0000496 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000497 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000498
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000499 if (Current.Type == TT_ObjCSelectorName &&
500 State.Stack.back().ColonPos == 0) {
501 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
502 State.Column + Spaces + Current.FormatTok.TokenLength)
503 State.Stack.back().ColonPos =
504 State.Stack.back().Indent + Current.LongestObjCSelectorName;
505 else
506 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000507 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000508 }
509
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000510 if (Current.Type != TT_LineComment &&
511 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
512 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000513 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000514 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000515 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000516
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000517 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000518 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
519 // Treat the condition inside an if as if it was a second function
520 // parameter, i.e. let nested calls have an indent of 4.
521 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000522 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000523 // Top-level spaces are exempt as that mostly leads to better results.
524 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000525 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000526 Previous.Type == TT_ConditionalExpr ||
527 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000528 getPrecedence(Previous) != prec::Assignment)
529 State.Stack.back().LastSpace = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000530 else if (Previous.ParameterCount > 1 &&
531 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000532 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000533 Previous.Type == TT_TemplateOpener))
534 // If this function has multiple parameters, indent nested calls from
535 // the start of the first parameter.
536 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000537 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000538
539 // If we break after an {, we should also break before the corresponding }.
540 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000541 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000542
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000543 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000544 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000545 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000546 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000547 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
548 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000549 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
550 Line.MustBeDeclaration))
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000551 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000552
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000553 // Any break on this level means that the parent level has been broken
554 // and we need to avoid bin packing there.
555 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000556 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000557 State.Stack[i].BreakBeforeParameter = true;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000558 }
559 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000560
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000561 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000562 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000563
Daniel Jasper20409152012-12-04 14:54:30 +0000564 /// \brief Mark the next token as consumed in \p State and modify its stacks
565 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000566 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000567 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000568 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000569
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000570 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
571 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000572 if (Current.is(tok::question))
573 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000574 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasperf343cab2013-01-31 14:59:26 +0000575 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000576 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
577 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000578 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000579
Daniel Jasper29f123b2013-02-08 15:28:42 +0000580 // Insert scopes created by fake parenthesis.
581 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
582 ParenState NewParenState = State.Stack.back();
583 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
584 State.Stack.push_back(NewParenState);
585 }
586
Daniel Jaspercf225b62012-12-24 13:43:52 +0000587 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000588 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000589 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
590 Current.is(tok::l_brace) ||
591 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000592 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000593 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000594 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000595 NewIndent = 2 + State.Stack.back().LastSpace;
596 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000597 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000598 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000599 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000600 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000601 State.Stack.push_back(
602 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
603 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000604 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000605 }
606
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000607 // If this '[' opens an ObjC call, determine whether all parameters fit into
608 // one line and put one per line if they don't.
609 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
610 Current.MatchingParen != NULL) {
611 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
612 State.Stack.back().BreakBeforeParameter = true;
613 }
614
Daniel Jaspercf225b62012-12-24 13:43:52 +0000615 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000616 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000617 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
618 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
619 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000620 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000621 --State.ParenLevel;
622 }
623
624 // Remove scopes created by fake parenthesis.
625 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
626 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000628
Daniel Jasper26f7e782013-01-08 14:56:18 +0000629 if (State.NextToken->Children.empty())
630 State.NextToken = NULL;
631 else
632 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000633
634 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000635 }
636
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000637 unsigned getColumnLimit() {
638 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
639 }
640
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000641 /// \brief An edge in the solution space starting from the \c LineState and
642 /// inserting a newline dependent on the \c bool.
643 typedef std::pair<bool, const LineState *> Edge;
644
645 /// \brief An item in the prioritized BFS search queue. The \c LineState was
646 /// reached using the \c Edge.
647 typedef std::pair<LineState, Edge> QueueItem;
648
649 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000650 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000651 /// This implements a variant of Dijkstra's algorithm on the graph that spans
652 /// the solution space (\c LineStates are the nodes). The algorithm tries to
653 /// find the shortest path (the one with lowest penalty) from \p InitialState
654 /// to a state where all tokens are placed.
655 unsigned analyzeSolutionSpace(const LineState &InitialState) {
656 // Insert start element into queue.
657 std::multimap<unsigned, QueueItem> Queue;
658 Queue.insert(std::pair<unsigned, QueueItem>(
Daniel Jasper01786732013-02-04 07:21:18 +0000659 0, QueueItem(InitialState, Edge(false, (const LineState *)0))));
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000660 std::map<LineState, Edge> Seen;
661
662 // While not empty, take first element and follow edges.
663 while (!Queue.empty()) {
664 unsigned Penalty = Queue.begin()->first;
665 QueueItem Item = Queue.begin()->second;
Daniel Jasper01786732013-02-04 07:21:18 +0000666 if (Item.first.NextToken == NULL) {
667 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000668 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000669 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000670 Queue.erase(Queue.begin());
671
672 if (Seen.find(Item.first) != Seen.end())
673 continue; // State already examined with lower penalty.
674
675 const LineState &SavedState = Seen.insert(std::pair<LineState, Edge>(
676 Item.first,
677 Edge(Item.second.first, Item.second.second))).first->first;
678
679 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ false, Queue);
680 addNextStateToQueue(SavedState, Penalty, /*NewLine=*/ true, Queue);
681 }
682
683 if (Queue.empty())
684 // We were unable to find a solution, do nothing.
685 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000686 return 0;
687
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000688 // Reconstruct the solution.
689 // FIXME: Add debugging output.
690 Edge *CurrentEdge = &Queue.begin()->second.second;
691 while (CurrentEdge->second != NULL) {
692 LineState CurrentState = *CurrentEdge->second;
Daniel Jasper01786732013-02-04 07:21:18 +0000693 if (CurrentEdge->first) {
694 DEBUG(llvm::errs() << "Penalty for splitting before "
695 << CurrentState.NextToken->FormatTok.Tok.getName()
696 << ": " << CurrentState.NextToken->SplitPenalty
697 << "\n");
698 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000699 addTokenToState(CurrentEdge->first, false, CurrentState);
700 CurrentEdge = &Seen[*CurrentEdge->second];
701 }
Daniel Jasper01786732013-02-04 07:21:18 +0000702 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000703
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000704 // Return the column after the last token of the solution.
705 return Queue.begin()->second.first.Column;
706 }
707
708 /// \brief Add the following state to the analysis queue \p Queue.
709 ///
710 /// Assume the current state is \p OldState and has been reached with a
711 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
712 void addNextStateToQueue(const LineState &OldState, unsigned Penalty,
713 bool NewLine,
714 std::multimap<unsigned, QueueItem> &Queue) {
715 if (NewLine && !canBreak(OldState))
716 return;
717 if (!NewLine && mustBreak(OldState))
718 return;
719 LineState State(OldState);
Daniel Jasperae8699b2013-01-28 09:35:24 +0000720 if (NewLine)
Daniel Jasper01786732013-02-04 07:21:18 +0000721 Penalty += State.NextToken->SplitPenalty;
Daniel Jasper20409152012-12-04 14:54:30 +0000722 addTokenToState(NewLine, true, State);
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000723 if (State.Column > getColumnLimit()) {
724 unsigned ExcessCharacters = State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000725 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000726 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000727 Queue.insert(std::pair<unsigned, QueueItem>(
728 Penalty, QueueItem(State, Edge(NewLine, &OldState))));
729 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000730
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000731 /// \brief Returns \c true, if a line break after \p State is allowed.
732 bool canBreak(const LineState &State) {
733 if (!State.NextToken->CanBreakBefore &&
734 !(State.NextToken->is(tok::r_brace) &&
735 State.Stack.back().BreakBeforeClosingBrace))
736 return false;
737 // Trying to insert a parameter on a new line if there are already more than
738 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000739 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000740 State.Stack.back().AvoidBinPacking)
741 return false;
742 return true;
743 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000744
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000745 /// \brief Returns \c true, if a line break after \p State is mandatory.
746 bool mustBreak(const LineState &State) {
747 if (State.NextToken->MustBreakBefore)
748 return true;
749 if (State.NextToken->is(tok::r_brace) &&
750 State.Stack.back().BreakBeforeClosingBrace)
751 return true;
752 if (State.NextToken->Parent->is(tok::semi) &&
753 State.LineContainsContinuedForLoopSection)
754 return true;
755 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000756 State.Stack.back().BreakBeforeParameter &&
Daniel Jaspercda16502013-02-04 08:34:57 +0000757 !isTrailingComment(*State.NextToken))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000758 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000759 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
760 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000761 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000762 State.NextToken->LongestObjCSelectorName == 0 &&
763 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000764 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000765 if ((State.NextToken->Type == TT_CtorInitializerColon ||
766 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000767 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000768 return true;
769 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000770 }
771
Daniel Jasperbac016b2012-12-03 18:12:45 +0000772 FormatStyle Style;
773 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000774 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000775 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000776 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000777 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000778};
779
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000780class LexerBasedFormatTokenSource : public FormatTokenSource {
781public:
782 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000783 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000784 IdentTable(Lex.getLangOpts()) {
785 Lex.SetKeepWhitespaceMode(true);
786 }
787
788 virtual FormatToken getNextToken() {
789 if (GreaterStashed) {
790 FormatTok.NewlinesBefore = 0;
791 FormatTok.WhiteSpaceStart =
792 FormatTok.Tok.getLocation().getLocWithOffset(1);
793 FormatTok.WhiteSpaceLength = 0;
794 GreaterStashed = false;
795 return FormatTok;
796 }
797
798 FormatTok = FormatToken();
799 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000800 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000801 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000802 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
803 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000804
805 // Consume and record whitespace until we find a significant token.
806 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000807 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000808 FormatTok.HasUnescapedNewline =
809 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000810 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
811
812 if (FormatTok.Tok.is(tok::eof))
813 return FormatTok;
814 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000815 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000816 }
Manuel Klimek95419382013-01-07 07:56:50 +0000817
818 // Now FormatTok is the next non-whitespace token.
819 FormatTok.TokenLength = Text.size();
820
Manuel Klimekd4397b92013-01-04 23:34:14 +0000821 // In case the token starts with escaped newlines, we want to
822 // take them into account as whitespace - this pattern is quite frequent
823 // in macro definitions.
824 // FIXME: What do we want to do with other escaped spaces, and escaped
825 // spaces or newlines in the middle of tokens?
826 // FIXME: Add a more explicit test.
827 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000828 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000829 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000830 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000831 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000832 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000833 }
834
835 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000836 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000837 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000838 FormatTok.Tok.setKind(Info.getTokenID());
839 }
840
841 if (FormatTok.Tok.is(tok::greatergreater)) {
842 FormatTok.Tok.setKind(tok::greater);
843 GreaterStashed = true;
844 }
845
846 return FormatTok;
847 }
848
849private:
850 FormatToken FormatTok;
851 bool GreaterStashed;
852 Lexer &Lex;
853 SourceManager &SourceMgr;
854 IdentifierTable IdentTable;
855
856 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000857 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000858 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
859 Tok.getLength());
860 }
861};
862
Daniel Jasperbac016b2012-12-03 18:12:45 +0000863class Formatter : public UnwrappedLineConsumer {
864public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000865 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
866 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000867 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000868 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000869 Whitespaces(SourceMgr), Ranges(Ranges) {
870 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000871
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000872 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000873
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000874 void deriveLocalStyle() {
875 unsigned CountBoundToVariable = 0;
876 unsigned CountBoundToType = 0;
877 bool HasCpp03IncompatibleFormat = false;
878 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
879 if (AnnotatedLines[i].First.Children.empty())
880 continue;
881 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
882 while (!Tok->Children.empty()) {
883 if (Tok->Type == TT_PointerOrReference) {
884 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
885 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
886 if (SpacesBefore && !SpacesAfter)
887 ++CountBoundToVariable;
888 else if (!SpacesBefore && SpacesAfter)
889 ++CountBoundToType;
890 }
891
Daniel Jasper29f123b2013-02-08 15:28:42 +0000892 if (Tok->Type == TT_TemplateCloser &&
893 Tok->Parent->Type == TT_TemplateCloser &&
894 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000895 HasCpp03IncompatibleFormat = true;
896 Tok = &Tok->Children[0];
897 }
898 }
899 if (Style.DerivePointerBinding) {
900 if (CountBoundToType > CountBoundToVariable)
901 Style.PointerBindsToType = true;
902 else if (CountBoundToType < CountBoundToVariable)
903 Style.PointerBindsToType = false;
904 }
905 if (Style.Standard == FormatStyle::LS_Auto) {
906 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
907 : FormatStyle::LS_Cpp03;
908 }
909 }
910
Daniel Jasperbac016b2012-12-03 18:12:45 +0000911 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000912 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000913 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000914 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000915 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000916 TokenAnnotator Annotator(Style, SourceMgr, Lex);
Daniel Jasper995e8202013-01-14 13:08:07 +0000917 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000918 Annotator.annotate(AnnotatedLines[i]);
919 }
920 deriveLocalStyle();
921 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
922 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +0000923 }
924 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
925 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000926 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000927 const AnnotatedLine &TheLine = *I;
928 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000929 unsigned Indent =
930 formatFirstToken(TheLine.First, TheLine.Level,
931 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000932 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +0000933 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000934 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +0000935 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000936 PreviousEndOfLineColumn = Formatter.format();
937 } else {
938 // If we did not reformat this unwrapped line, the column at the end of
939 // the last token is unchanged - thus, we can calculate the end of the
940 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000941 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +0000942 SourceMgr.getSpellingColumnNumber(
943 TheLine.Last->FormatTok.Tok.getLocation()) +
944 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000945 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000946 }
947 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000948 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000949 }
950
951private:
Manuel Klimek517e8942013-01-11 17:54:10 +0000952 /// \brief Tries to merge lines into one.
953 ///
954 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
955 /// if possible; note that \c I will be incremented when lines are merged.
956 ///
957 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000958 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +0000959 std::vector<AnnotatedLine>::iterator &I,
960 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +0000961 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
962
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000963 // We can never merge stuff if there are trailing line comments.
964 if (I->Last->Type == TT_LineComment)
965 return;
966
Manuel Klimek517e8942013-01-11 17:54:10 +0000967 // Check whether the UnwrappedLine can be put onto a single line. If
968 // so, this is bound to be the optimal solution (by definition) and we
969 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000970 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000971 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000972 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +0000973
Daniel Jasper9c8c40e2013-01-21 14:18:28 +0000974 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000975 return;
Manuel Klimek517e8942013-01-11 17:54:10 +0000976
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000977 if (I->Last->is(tok::l_brace)) {
978 tryMergeSimpleBlock(I, E, Limit);
979 } else if (I->First.is(tok::kw_if)) {
980 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000981 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
982 I->First.FormatTok.IsFirst)) {
983 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000984 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000985 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000986 }
987
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000988 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
989 std::vector<AnnotatedLine>::iterator E,
990 unsigned Limit) {
991 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +0000992 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
993 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000994 if (I + 2 != E && (I + 2)->InPPDirective &&
995 !(I + 2)->First.FormatTok.HasUnescapedNewline)
996 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +0000997 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000998 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +0000999 join(Line, *(++I));
1000 }
1001
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001002 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1003 std::vector<AnnotatedLine>::iterator E,
1004 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001005 if (!Style.AllowShortIfStatementsOnASingleLine)
1006 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001007 if ((I + 1)->InPPDirective != I->InPPDirective ||
1008 ((I + 1)->InPPDirective &&
1009 (I + 1)->First.FormatTok.HasUnescapedNewline))
1010 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001011 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001012 if (Line.Last->isNot(tok::r_paren))
1013 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001014 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001015 return;
1016 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1017 return;
1018 // Only inline simple if's (no nested if or else).
1019 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1020 return;
1021 join(Line, *(++I));
1022 }
1023
1024 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001025 std::vector<AnnotatedLine>::iterator E,
1026 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001027 // First, check that the current line allows merging. This is the case if
1028 // we're not in a control flow statement and the last token is an opening
1029 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001030 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001031 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001032 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1033 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1034 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1035 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001036 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001037 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1038 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001039 if (!AllowedTokens)
1040 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001041
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001042 AnnotatedToken *Tok = &(I + 1)->First;
1043 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1044 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1045 Tok->SpaceRequiredBefore = false;
1046 join(Line, *(I + 1));
1047 I += 1;
1048 } else {
1049 // Check that we still have three lines and they fit into the limit.
1050 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1051 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001052 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001053
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001054 // Second, check that the next line does not contain any braces - if it
1055 // does, readability declines when putting it into a single line.
1056 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1057 return;
1058 do {
1059 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1060 return;
1061 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1062 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001063
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001064 // Last, check that the third line contains a single closing brace.
1065 Tok = &(I + 2)->First;
1066 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1067 Tok->MustBreakBefore)
1068 return;
1069
1070 join(Line, *(I + 1));
1071 join(Line, *(I + 2));
1072 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001073 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001074 }
1075
1076 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1077 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001078 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1079 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001080 }
1081
Daniel Jasper995e8202013-01-14 13:08:07 +00001082 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1083 A.Last->Children.push_back(B.First);
1084 while (!A.Last->Children.empty()) {
1085 A.Last->Children[0].Parent = A.Last;
1086 A.Last = &A.Last->Children[0];
1087 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001088 }
1089
Daniel Jasper995e8202013-01-14 13:08:07 +00001090 bool touchesRanges(const AnnotatedLine &TheLine) {
1091 const FormatToken *First = &TheLine.First.FormatTok;
1092 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001093 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001094 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001095 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001096 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1097 Ranges[i].getBegin()) &&
1098 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1099 LineRange.getBegin()))
1100 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001101 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001102 return false;
1103 }
1104
1105 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001106 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001107 }
1108
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001109 /// \brief Add a new line and the required indent before the first Token
1110 /// of the \c UnwrappedLine if there was no structural parsing error.
1111 /// Returns the indent level of the \c UnwrappedLine.
1112 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1113 bool InPPDirective,
1114 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001115 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001116 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1117 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1118
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001119 unsigned Newlines =
1120 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001121 if (Newlines == 0 && !Tok.IsFirst)
1122 Newlines = 1;
1123 unsigned Indent = Level * 2;
1124
1125 bool IsAccessModifier = false;
1126 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1127 RootToken.is(tok::kw_private))
1128 IsAccessModifier = true;
1129 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1130 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1131 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1132 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1133 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1134 IsAccessModifier = true;
1135
1136 if (IsAccessModifier &&
1137 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1138 Indent += Style.AccessModifierOffset;
1139 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001140 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001141 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001142 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1143 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001144 }
1145 return Indent;
1146 }
1147
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001148 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001149 FormatStyle Style;
1150 Lexer &Lex;
1151 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001152 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001153 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001154 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001155 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001156};
1157
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001158tooling::Replacements
1159reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1160 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001161 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001162 OwningPtr<DiagnosticConsumer> DiagPrinter;
1163 if (DiagClient == 0) {
1164 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1165 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1166 DiagClient = DiagPrinter.get();
1167 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001168 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001169 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001170 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001171 Diagnostics.setSourceManager(&SourceMgr);
1172 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001173 return formatter.format();
1174}
1175
Daniel Jasper46ef8522013-01-10 13:08:12 +00001176LangOptions getFormattingLangOpts() {
1177 LangOptions LangOpts;
1178 LangOpts.CPlusPlus = 1;
1179 LangOpts.CPlusPlus11 = 1;
1180 LangOpts.Bool = 1;
1181 LangOpts.ObjC1 = 1;
1182 LangOpts.ObjC2 = 1;
1183 return LangOpts;
1184}
1185
Daniel Jaspercd162382013-01-07 13:26:07 +00001186} // namespace format
1187} // namespace clang