blob: 35389d140d18a3f0540d01a7bfe21d353c4660a2 [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 Jasperd75ff642013-01-28 15:40:20 +000046 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000047 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000048 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000049 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasper01786732013-02-04 07:21:18 +000050 LLVMStyle.PenaltyExcessCharacter = 1000000;
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 Jasper0df6acd2013-01-16 14:59:02 +000064 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +000065 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +000066 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +000067 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +000068 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +000069 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasper01786732013-02-04 07:21:18 +000070 GoogleStyle.PenaltyExcessCharacter = 1000000;
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 Jasper8ff690a2013-02-06 14:22:40 +000077 ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
78 ChromiumStyle.DerivePointerBinding = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +000079 return ChromiumStyle;
80}
81
Daniel Jasper15417ef2013-02-06 20:07:35 +000082static bool isTrailingComment(const AnnotatedToken &Tok) {
83 return Tok.is(tok::comment) &&
84 (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
85}
86
Daniel Jasperce3d1a62013-02-08 08:22:00 +000087// Returns the length of everything up to the first possible line break after
88// the ), ], } or > matching \c Tok.
89static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
90 if (Tok.MatchingParen == NULL)
91 return 0;
92 AnnotatedToken *End = Tok.MatchingParen;
93 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
94 End = &End->Children[0];
95 }
96 return End->TotalLength - Tok.TotalLength + 1;
97}
98
Daniel Jasperdcc2a622013-01-18 08:44:07 +000099/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000100///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000101/// This includes special handling for certain constructs, e.g. the alignment of
102/// trailing line comments.
103class WhitespaceManager {
104public:
105 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
106
107 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
108 /// each \c AnnotatedToken.
109 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
110 unsigned Spaces, unsigned WhitespaceStartColumn,
111 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000112 // 2+ newlines mean an empty line separating logic scopes.
113 if (NewLines >= 2)
114 alignComments();
115
116 // Align line comments if they are trailing or if they continue other
117 // trailing comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000118 if (isTrailingComment(Tok) && (Tok.Parent != NULL || !Comments.empty())) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000119 if (Style.ColumnLimit >=
120 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
121 Comments.push_back(StoredComment());
122 Comments.back().Tok = Tok.FormatTok;
123 Comments.back().Spaces = Spaces;
124 Comments.back().NewLines = NewLines;
Daniel Jasper474e4622013-02-06 22:04:05 +0000125 if (NewLines == 0)
126 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
127 else
128 Comments.back().MinColumn = Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000129 Comments.back().MaxColumn =
130 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000131 return;
132 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000133 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000134
135 // If this line does not have a trailing comment, align the stored comments.
Daniel Jasper15417ef2013-02-06 20:07:35 +0000136 if (Tok.Children.empty() && !isTrailingComment(Tok))
Daniel Jasper821627e2013-01-21 22:49:20 +0000137 alignComments();
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000138 storeReplacement(Tok.FormatTok,
139 std::string(NewLines, '\n') + std::string(Spaces, ' '));
140 }
141
142 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
143 /// backslashes to escape newlines inside a preprocessor directive.
144 ///
145 /// This function and \c replaceWhitespace have the same behavior if
146 /// \c Newlines == 0.
147 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
148 unsigned Spaces, unsigned WhitespaceStartColumn,
149 const FormatStyle &Style) {
150 std::string NewLineText;
151 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000152 unsigned Offset =
153 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000154 for (unsigned i = 0; i < NewLines; ++i) {
155 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
156 NewLineText += "\\\n";
157 Offset = 0;
158 }
159 }
160 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
161 }
162
163 /// \brief Returns all the \c Replacements created during formatting.
164 const tooling::Replacements &generateReplacements() {
165 alignComments();
166 return Replaces;
167 }
168
169private:
170 /// \brief Structure to store a comment for later layout and alignment.
171 struct StoredComment {
172 FormatToken Tok;
173 unsigned MinColumn;
174 unsigned MaxColumn;
175 unsigned NewLines;
176 unsigned Spaces;
177 };
178 SmallVector<StoredComment, 16> Comments;
179 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
180
181 /// \brief Try to align all stashed comments.
182 void alignComments() {
183 unsigned MinColumn = 0;
184 unsigned MaxColumn = UINT_MAX;
185 comment_iterator Start = Comments.begin();
186 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
187 ++I) {
188 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
189 alignComments(Start, I, MinColumn);
190 MinColumn = I->MinColumn;
191 MaxColumn = I->MaxColumn;
192 Start = I;
193 } else {
194 MinColumn = std::max(MinColumn, I->MinColumn);
195 MaxColumn = std::min(MaxColumn, I->MaxColumn);
196 }
197 }
198 alignComments(Start, Comments.end(), MinColumn);
199 Comments.clear();
200 }
201
202 /// \brief Put all the comments between \p I and \p E into \p Column.
203 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
204 while (I != E) {
205 unsigned Spaces = I->Spaces + Column - I->MinColumn;
206 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
Daniel Jasper29f123b2013-02-08 15:28:42 +0000207 std::string(Spaces, ' '));
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000208 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000209 }
210 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000211
212 /// \brief Stores \p Text as the replacement for the whitespace in front of
213 /// \p Tok.
214 void storeReplacement(const FormatToken &Tok, const std::string Text) {
Daniel Jasperafcbd852013-01-30 09:46:12 +0000215 // Don't create a replacement, if it does not change anything.
216 if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
217 Tok.WhiteSpaceLength) == Text)
218 return;
219
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000220 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
221 Tok.WhiteSpaceLength, Text));
222 }
223
224 SourceManager &SourceMgr;
225 tooling::Replacements Replaces;
226};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000227
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228class UnwrappedLineFormatter {
229public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000230 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000231 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000232 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000233 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000234 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000235 FirstIndent(FirstIndent), RootToken(RootToken),
236 Whitespaces(Whitespaces) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000237 }
238
Manuel Klimekd4397b92013-01-04 23:34:14 +0000239 /// \brief Formats an \c UnwrappedLine.
240 ///
241 /// \returns The column after the last token in the last line of the
242 /// \c UnwrappedLine.
243 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000244 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000245 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000246 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000247 State.NextToken = &RootToken;
Daniel Jasperd399bff2013-02-05 09:41:21 +0000248 State.Stack.push_back(
249 ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters,
250 /*HasMultiParameterLine=*/ false));
Daniel Jasper2e603772013-01-29 11:21:01 +0000251 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000252 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000253 State.ParenLevel = 0;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000254
Manuel Klimekca547db2013-01-16 14:55:28 +0000255 DEBUG({
256 DebugTokenState(*State.NextToken);
257 });
258
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000259 // The first token has already been indented and thus consumed.
260 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000262 // If everything fits on a single line, just put it there.
263 if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
264 while (State.NextToken != NULL) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000265 addTokenToState(false, false, State);
Daniel Jasper1321eb52012-12-18 21:05:13 +0000266 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000267 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000268 }
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000269
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000270 // If the ObjC method declaration does not fit on a line, we should format
271 // it with one arg per line.
272 if (Line.Type == LT_ObjCMethodDecl)
273 State.Stack.back().BreakBeforeParameter = true;
274
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000275 // Find best solution in solution space.
276 return analyzeSolutionSpace(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000277 }
278
279private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000280 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
281 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000282 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
283 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000284 llvm::errs();
285 }
286
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000287 struct ParenState {
Daniel Jasperd399bff2013-02-05 09:41:21 +0000288 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
289 bool HasMultiParameterLine)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000290 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
291 BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000292 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000293 HasMultiParameterLine(HasMultiParameterLine), ColonPos(0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000294 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000295
Daniel Jasperbac016b2012-12-03 18:12:45 +0000296 /// \brief The position to which a specific parenthesis level needs to be
297 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000298 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000299
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000300 /// \brief The position of the last space on each level.
301 ///
302 /// Used e.g. to break like:
303 /// functionCall(Parameter, otherCall(
304 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000305 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000306
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000307 /// \brief The position the first "<<" operator encountered on each level.
308 ///
309 /// Used to align "<<" operators. 0 if no such operator has been encountered
310 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000311 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000312
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000313 /// \brief Whether a newline needs to be inserted before the block's closing
314 /// brace.
315 ///
316 /// We only want to insert a newline before the closing brace if there also
317 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000318 bool BreakBeforeClosingBrace;
319
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000320 /// \brief The column of a \c ? in a conditional expression;
321 unsigned QuestionColumn;
322
Daniel Jasperf343cab2013-01-31 14:59:26 +0000323 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
324 /// lines, in this context.
325 bool AvoidBinPacking;
326
327 /// \brief Break after the next comma (or all the commas in this context if
328 /// \c AvoidBinPacking is \c true).
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000329 bool BreakBeforeParameter;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000330
331 /// \brief This context already has a line with more than one parameter.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000332 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000333
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000334 /// \brief The position of the colon in an ObjC method declaration/call.
335 unsigned ColonPos;
336
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000337 bool operator<(const ParenState &Other) const {
338 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000339 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000340 if (LastSpace != Other.LastSpace)
341 return LastSpace < Other.LastSpace;
342 if (FirstLessLess != Other.FirstLessLess)
343 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000344 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
345 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000346 if (QuestionColumn != Other.QuestionColumn)
347 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000348 if (AvoidBinPacking != Other.AvoidBinPacking)
349 return AvoidBinPacking;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000350 if (BreakBeforeParameter != Other.BreakBeforeParameter)
351 return BreakBeforeParameter;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000352 if (HasMultiParameterLine != Other.HasMultiParameterLine)
353 return HasMultiParameterLine;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000354 if (ColonPos != Other.ColonPos)
355 return ColonPos < Other.ColonPos;
Daniel Jasperb3123142013-01-12 07:36:22 +0000356 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000357 }
358 };
359
360 /// \brief The current state when indenting a unwrapped line.
361 ///
362 /// As the indenting tries different combinations this is copied by value.
363 struct LineState {
364 /// \brief The number of used columns in the current line.
365 unsigned Column;
366
367 /// \brief The token that needs to be next formatted.
368 const AnnotatedToken *NextToken;
369
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000370 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000371 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000372 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000373 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000374
375 /// \brief \c true if this line contains a continued for-loop section.
376 bool LineContainsContinuedForLoopSection;
377
Daniel Jasper29f123b2013-02-08 15:28:42 +0000378 /// \brief The level of nesting inside (), [], <> and {}.
379 unsigned ParenLevel;
380
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000381 /// \brief A stack keeping track of properties applying to parenthesis
382 /// levels.
383 std::vector<ParenState> Stack;
384
385 /// \brief Comparison operator to be able to used \c LineState in \c map.
386 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000387 if (Other.NextToken != NextToken)
388 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000389 if (Other.Column != Column)
390 return Other.Column > Column;
Daniel Jasper2e603772013-01-29 11:21:01 +0000391 if (Other.VariablePos != VariablePos)
392 return Other.VariablePos < VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000393 if (Other.LineContainsContinuedForLoopSection !=
394 LineContainsContinuedForLoopSection)
395 return LineContainsContinuedForLoopSection;
Daniel Jasper29f123b2013-02-08 15:28:42 +0000396 if (Other.ParenLevel != ParenLevel)
397 return Other.ParenLevel < ParenLevel;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000398 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399 }
400 };
401
Daniel Jasper20409152012-12-04 14:54:30 +0000402 /// \brief Appends the next token to \p State and updates information
403 /// necessary for indentation.
404 ///
405 /// Puts the token on the current line if \p Newline is \c true and adds a
406 /// line break and necessary indentation otherwise.
407 ///
408 /// If \p DryRun is \c false, also creates and stores the required
409 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000410 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000411 const AnnotatedToken &Current = *State.NextToken;
412 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000413 assert(State.Stack.size());
Daniel Jasperbac016b2012-12-03 18:12:45 +0000414
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000415 if (Current.Type == TT_ImplicitStringLiteral) {
416 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
417 State.NextToken->FormatTok.TokenLength;
418 if (State.NextToken->Children.empty())
419 State.NextToken = NULL;
420 else
421 State.NextToken = &State.NextToken->Children[0];
422 return;
423 }
424
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000426 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000427 if (Current.is(tok::r_brace)) {
428 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000429 } else if (Current.is(tok::string_literal) &&
430 Previous.is(tok::string_literal)) {
431 State.Column = State.Column - Previous.FormatTok.TokenLength;
432 } else if (Current.is(tok::lessless) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000433 State.Stack.back().FirstLessLess != 0) {
434 State.Column = State.Stack.back().FirstLessLess;
435 } else if (State.ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000436 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000437 Current.is(tok::period) || Current.is(tok::arrow) ||
438 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000439 // Indent and extra 4 spaces after if we know the current expression is
440 // continued. Don't do that on the top level, as we already indent 4
441 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000442 State.Column = std::max(State.Stack.back().LastSpace,
443 State.Stack.back().Indent) + 4;
444 } else if (Current.Type == TT_ConditionalExpr) {
445 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000446 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000447 ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
448 State.ParenLevel == 0)) {
Daniel Jasper2e603772013-01-29 11:21:01 +0000449 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000450 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
451 Current.Type == TT_StartOfName) {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000452 State.Column = State.Stack.back().Indent - 4;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000453 } else if (Current.Type == TT_ObjCSelectorName) {
454 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
455 State.Column =
456 State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
457 } else {
458 State.Column = State.Stack.back().Indent;
459 State.Stack.back().ColonPos =
460 State.Column + Current.FormatTok.TokenLength;
461 }
462 } else if (Previous.Type == TT_ObjCMethodExpr) {
463 State.Column = State.Stack.back().Indent + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000464 } else {
Daniel Jasper29f123b2013-02-08 15:28:42 +0000465 State.Column = State.Stack.back().Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000466 }
467
Daniel Jasperf343cab2013-01-31 14:59:26 +0000468 if (Previous.is(tok::comma) && !State.Stack.back().AvoidBinPacking)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000469 State.Stack.back().BreakBeforeParameter = false;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000470
Daniel Jasper26f7e782013-01-08 14:56:18 +0000471 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000472 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000473
Manuel Klimek060143e2013-01-02 18:33:23 +0000474 if (!DryRun) {
475 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000476 Whitespaces.replaceWhitespace(Current, 1, State.Column,
477 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000478 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000479 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
480 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000481 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000482
Daniel Jasper29f123b2013-02-08 15:28:42 +0000483 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000484 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper29f123b2013-02-08 15:28:42 +0000485 State.Stack.back().Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000486 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000487 if (Current.is(tok::equal) &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000488 (RootToken.is(tok::kw_for) || State.ParenLevel == 0))
Daniel Jasper2e603772013-01-29 11:21:01 +0000489 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000490
Daniel Jasper729a7432013-02-11 12:36:37 +0000491 unsigned Spaces = State.NextToken->SpacesRequiredBefore;
Daniel Jasper20409152012-12-04 14:54:30 +0000492
Daniel Jasperbac016b2012-12-03 18:12:45 +0000493 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000494 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000495
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000496 if (Current.Type == TT_ObjCSelectorName &&
497 State.Stack.back().ColonPos == 0) {
498 if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
499 State.Column + Spaces + Current.FormatTok.TokenLength)
500 State.Stack.back().ColonPos =
501 State.Stack.back().Indent + Current.LongestObjCSelectorName;
502 else
503 State.Stack.back().ColonPos =
Daniel Jasper9e9e6e02013-02-06 16:00:26 +0000504 State.Column + Spaces + Current.FormatTok.TokenLength;
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000505 }
506
Daniel Jasperd4f2c2e2013-01-29 19:41:55 +0000507 if (Current.Type != TT_LineComment &&
508 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
509 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000510 State.Stack.back().Indent = State.Column + Spaces;
Daniel Jaspercda16502013-02-04 08:34:57 +0000511 if (Previous.is(tok::comma) && !isTrailingComment(Current))
Daniel Jasper29f123b2013-02-08 15:28:42 +0000512 State.Stack.back().HasMultiParameterLine = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000513
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000514 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000515 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
516 // Treat the condition inside an if as if it was a second function
517 // parameter, i.e. let nested calls have an indent of 4.
518 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper29f123b2013-02-08 15:28:42 +0000519 else if (Previous.is(tok::comma) && State.ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000520 // Top-level spaces are exempt as that mostly leads to better results.
521 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000522 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000523 Previous.Type == TT_ConditionalExpr ||
524 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000525 getPrecedence(Previous) != prec::Assignment)
526 State.Stack.back().LastSpace = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000527 else if (Previous.ParameterCount > 1 &&
528 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
Daniel Jasperf343cab2013-01-31 14:59:26 +0000529 Previous.is(tok::l_brace) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +0000530 Previous.Type == TT_TemplateOpener))
531 // If this function has multiple parameters, indent nested calls from
532 // the start of the first parameter.
533 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000534 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000535
536 // If we break after an {, we should also break before the corresponding }.
537 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000538 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000539
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000540 if (State.Stack.back().AvoidBinPacking && Newline &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000541 (Line.First.isNot(tok::kw_for) || State.ParenLevel != 1)) {
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000542 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000543 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000544 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
545 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000546 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
547 Line.MustBeDeclaration))
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000548 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000549
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000550 // Any break on this level means that the parent level has been broken
551 // and we need to avoid bin packing there.
552 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
Daniel Jasper8159d2f2013-02-04 07:30:30 +0000553 if (Line.First.isNot(tok::kw_for) || i != 1)
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000554 State.Stack[i].BreakBeforeParameter = true;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000555 }
556 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000557
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000558 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000559 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560
Daniel Jasper20409152012-12-04 14:54:30 +0000561 /// \brief Mark the next token as consumed in \p State and modify its stacks
562 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000563 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000564 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000565 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000566
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000567 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
568 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000569 if (Current.is(tok::question))
570 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000571 if (Current.is(tok::l_brace) && Current.MatchingParen != NULL &&
Daniel Jasperf343cab2013-01-31 14:59:26 +0000572 !Current.MatchingParen->MustBreakBefore) {
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000573 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
574 State.Stack.back().BreakBeforeParameter = true;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000575 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000576
Daniel Jasper29f123b2013-02-08 15:28:42 +0000577 // Insert scopes created by fake parenthesis.
578 for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
579 ParenState NewParenState = State.Stack.back();
580 NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
581 State.Stack.push_back(NewParenState);
582 }
583
Daniel Jaspercf225b62012-12-24 13:43:52 +0000584 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000585 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000586 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
587 Current.is(tok::l_brace) ||
588 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000589 unsigned NewIndent;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000590 bool AvoidBinPacking;
Manuel Klimek2851c162013-01-10 14:36:46 +0000591 if (Current.is(tok::l_brace)) {
Daniel Jasperf343cab2013-01-31 14:59:26 +0000592 NewIndent = 2 + State.Stack.back().LastSpace;
593 AvoidBinPacking = false;
Manuel Klimek2851c162013-01-10 14:36:46 +0000594 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000595 NewIndent = 4 + State.Stack.back().LastSpace;
Daniel Jasperf343cab2013-01-31 14:59:26 +0000596 AvoidBinPacking = !Style.BinPackParameters;
Manuel Klimek2851c162013-01-10 14:36:46 +0000597 }
Daniel Jasperd399bff2013-02-05 09:41:21 +0000598 State.Stack.push_back(
599 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
600 State.Stack.back().HasMultiParameterLine));
Daniel Jasper29f123b2013-02-08 15:28:42 +0000601 ++State.ParenLevel;
Daniel Jasper20409152012-12-04 14:54:30 +0000602 }
603
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000604 // If this '[' opens an ObjC call, determine whether all parameters fit into
605 // one line and put one per line if they don't.
606 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
607 Current.MatchingParen != NULL) {
608 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
609 State.Stack.back().BreakBeforeParameter = true;
610 }
611
Daniel Jaspercf225b62012-12-24 13:43:52 +0000612 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000613 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000614 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
615 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
616 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000617 State.Stack.pop_back();
Daniel Jasper29f123b2013-02-08 15:28:42 +0000618 --State.ParenLevel;
619 }
620
621 // Remove scopes created by fake parenthesis.
622 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
623 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000624 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000625
Daniel Jasper26f7e782013-01-08 14:56:18 +0000626 if (State.NextToken->Children.empty())
627 State.NextToken = NULL;
628 else
629 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000630
631 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000632 }
633
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000634 unsigned getColumnLimit() {
635 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
636 }
637
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000638 /// \brief An edge in the solution space from \c Previous->State to \c State,
639 /// inserting a newline dependent on the \c NewLine.
640 struct StateNode {
641 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
642 : State(State), NewLine(NewLine), Previous(Previous) {
643 }
644 LineState State;
645 bool NewLine;
646 StateNode *Previous;
647 };
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000648
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000649 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
650 ///
651 /// In case of equal penalties, we want to prefer states that were inserted
652 /// first. During state generation we make sure that we insert states first
653 /// that break the line as late as possible.
654 typedef std::pair<unsigned, unsigned> OrderedPenalty;
655
656 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
657 /// \c State has the given \c OrderedPenalty.
658 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
659
660 /// \brief The BFS queue type.
661 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
662 std::greater<QueueItem> > QueueType;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000663
664 /// \brief Analyze the entire solution space starting from \p InitialState.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000665 ///
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000666 /// This implements a variant of Dijkstra's algorithm on the graph that spans
667 /// the solution space (\c LineStates are the nodes). The algorithm tries to
668 /// find the shortest path (the one with lowest penalty) from \p InitialState
669 /// to a state where all tokens are placed.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000670 unsigned analyzeSolutionSpace(LineState &InitialState) {
671 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
672
673 // Increasing count of \c StateNode items we have created. This is used
674 // to create a deterministic order independent of the container.
675 unsigned Count = 0;
676 QueueType Queue;
677
678 std::set<LineState> Seen;
679
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000680 // Insert start element into queue.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000681 StateNode *Node=
682 new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
683 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
684 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000685
686 // While not empty, take first element and follow edges.
687 while (!Queue.empty()) {
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000688 unsigned Penalty = Queue.top().first.first;
689 StateNode *Node= Queue.top().second;
690 if (Node->State.NextToken == NULL) {
Daniel Jasper01786732013-02-04 07:21:18 +0000691 DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000692 break;
Daniel Jasper01786732013-02-04 07:21:18 +0000693 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000694 Queue.pop();
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000695
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000696 if (!Seen.insert(Node->State).second)
697 // State already examined with lower penalty.
698 continue;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000699
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000700 addNextStateToQueue(Allocator, Queue, Count, Penalty, Node,
701 /*NewLine=*/ false);
702 addNextStateToQueue(Allocator, Queue, Count, Penalty, Node,
703 /*NewLine=*/ true);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000704 }
705
706 if (Queue.empty())
707 // We were unable to find a solution, do nothing.
708 // FIXME: Add diagnostic?
Daniel Jasperbac016b2012-12-03 18:12:45 +0000709 return 0;
710
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000711 // Reconstruct the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000712 reconstructPath(InitialState, Queue.top().second);
Daniel Jasper01786732013-02-04 07:21:18 +0000713 DEBUG(llvm::errs() << "---\n");
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000715 // Return the column after the last token of the solution.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000716 return Queue.top().second->State.Column;
717 }
718
719 void reconstructPath(LineState &State, StateNode *Current) {
720 // FIXME: This recursive implementation limits the possible number
721 // of tokens per line if compiled into a binary with small stack space.
722 // To become more independent of stack frame limitations we would need
723 // to also change the TokenAnnotator.
724 if (Current->Previous == NULL)
725 return;
726 reconstructPath(State, Current->Previous);
727 DEBUG({
728 if (Current->NewLine) {
729 llvm::errs() << "Penalty for splitting before "
730 << Current->State.NextToken->FormatTok.Tok.getName()
731 << ": " << Current->State.NextToken->SplitPenalty << "\n";
732 }
733 });
734 addTokenToState(Current->NewLine, false, State);
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000735 }
736
737 /// \brief Add the following state to the analysis queue \p Queue.
738 ///
739 /// Assume the current state is \p OldState and has been reached with a
740 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000741 void addNextStateToQueue(llvm::SpecificBumpPtrAllocator<StateNode> &Allocator,
742 QueueType &Queue, unsigned &Count, unsigned Penalty,
743 StateNode *PreviousNode, bool NewLine) {
744 if (NewLine && !canBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000745 return;
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000746 if (!NewLine && mustBreak(PreviousNode->State))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000747 return;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000748 if (NewLine)
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000749 Penalty += PreviousNode->State.NextToken->SplitPenalty;
750
751 StateNode *Node = new (Allocator.Allocate())
752 StateNode(PreviousNode->State, NewLine, PreviousNode);
753 addTokenToState(NewLine, true, Node->State);
754 if (Node->State.Column > getColumnLimit()) {
755 unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
Daniel Jasper01786732013-02-04 07:21:18 +0000756 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000757 }
Manuel Klimek32a2fd72013-02-13 10:46:36 +0000758
759 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
760 ++Count;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000761 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000762
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000763 /// \brief Returns \c true, if a line break after \p State is allowed.
764 bool canBreak(const LineState &State) {
765 if (!State.NextToken->CanBreakBefore &&
766 !(State.NextToken->is(tok::r_brace) &&
767 State.Stack.back().BreakBeforeClosingBrace))
768 return false;
769 // Trying to insert a parameter on a new line if there are already more than
770 // one parameter on the current line is bin packing.
Daniel Jasperd399bff2013-02-05 09:41:21 +0000771 if (State.Stack.back().HasMultiParameterLine &&
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000772 State.Stack.back().AvoidBinPacking)
773 return false;
774 return true;
775 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000776
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000777 /// \brief Returns \c true, if a line break after \p State is mandatory.
778 bool mustBreak(const LineState &State) {
779 if (State.NextToken->MustBreakBefore)
780 return true;
781 if (State.NextToken->is(tok::r_brace) &&
782 State.Stack.back().BreakBeforeClosingBrace)
783 return true;
784 if (State.NextToken->Parent->is(tok::semi) &&
785 State.LineContainsContinuedForLoopSection)
786 return true;
787 if (State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000788 State.Stack.back().BreakBeforeParameter &&
Daniel Jaspercda16502013-02-04 08:34:57 +0000789 !isTrailingComment(*State.NextToken))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000790 return true;
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000791 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
792 // out whether it is the first parameter. Clean this up.
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000793 if (State.NextToken->Type == TT_ObjCSelectorName &&
Daniel Jasperce3d1a62013-02-08 08:22:00 +0000794 State.NextToken->LongestObjCSelectorName == 0 &&
795 State.Stack.back().BreakBeforeParameter)
Daniel Jasper63d7ced2013-02-05 10:07:47 +0000796 return true;
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000797 if ((State.NextToken->Type == TT_CtorInitializerColon ||
798 (State.NextToken->Parent->ClosesTemplateDeclaration &&
Daniel Jasper29f123b2013-02-08 15:28:42 +0000799 State.ParenLevel == 0)))
Daniel Jasper68ef0df2013-02-01 11:00:45 +0000800 return true;
801 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000802 }
803
Daniel Jasperbac016b2012-12-03 18:12:45 +0000804 FormatStyle Style;
805 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000806 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000807 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000808 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000809 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000810};
811
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000812class LexerBasedFormatTokenSource : public FormatTokenSource {
813public:
814 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000815 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000816 IdentTable(Lex.getLangOpts()) {
817 Lex.SetKeepWhitespaceMode(true);
818 }
819
820 virtual FormatToken getNextToken() {
821 if (GreaterStashed) {
822 FormatTok.NewlinesBefore = 0;
823 FormatTok.WhiteSpaceStart =
824 FormatTok.Tok.getLocation().getLocWithOffset(1);
825 FormatTok.WhiteSpaceLength = 0;
826 GreaterStashed = false;
827 return FormatTok;
828 }
829
830 FormatTok = FormatToken();
831 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000832 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000833 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000834 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
835 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000836
837 // Consume and record whitespace until we find a significant token.
838 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka28fc062013-02-11 12:33:24 +0000839 unsigned Newlines = Text.count('\n');
840 unsigned EscapedNewlines = Text.count("\\\n");
841 FormatTok.NewlinesBefore += Newlines;
842 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000843 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
844
845 if (FormatTok.Tok.is(tok::eof))
846 return FormatTok;
847 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +0000848 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +0000849 }
Manuel Klimek95419382013-01-07 07:56:50 +0000850
851 // Now FormatTok is the next non-whitespace token.
852 FormatTok.TokenLength = Text.size();
853
Manuel Klimekd4397b92013-01-04 23:34:14 +0000854 // In case the token starts with escaped newlines, we want to
855 // take them into account as whitespace - this pattern is quite frequent
856 // in macro definitions.
857 // FIXME: What do we want to do with other escaped spaces, and escaped
858 // spaces or newlines in the middle of tokens?
859 // FIXME: Add a more explicit test.
860 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000861 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +0000862 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +0000863 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +0000864 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000865 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000866 }
867
868 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +0000869 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000870 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000871 FormatTok.Tok.setKind(Info.getTokenID());
872 }
873
874 if (FormatTok.Tok.is(tok::greatergreater)) {
875 FormatTok.Tok.setKind(tok::greater);
876 GreaterStashed = true;
877 }
878
879 return FormatTok;
880 }
881
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000882 IdentifierTable &getIdentTable() { return IdentTable; }
883
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000884private:
885 FormatToken FormatTok;
886 bool GreaterStashed;
887 Lexer &Lex;
888 SourceManager &SourceMgr;
889 IdentifierTable IdentTable;
890
891 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +0000892 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000893 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
894 Tok.getLength());
895 }
896};
897
Daniel Jasperbac016b2012-12-03 18:12:45 +0000898class Formatter : public UnwrappedLineConsumer {
899public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +0000900 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
901 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000902 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000903 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000904 Whitespaces(SourceMgr), Ranges(Ranges) {
905 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000906
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000907 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000908
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000909 void deriveLocalStyle() {
910 unsigned CountBoundToVariable = 0;
911 unsigned CountBoundToType = 0;
912 bool HasCpp03IncompatibleFormat = false;
913 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
914 if (AnnotatedLines[i].First.Children.empty())
915 continue;
916 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
917 while (!Tok->Children.empty()) {
918 if (Tok->Type == TT_PointerOrReference) {
919 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
920 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
921 if (SpacesBefore && !SpacesAfter)
922 ++CountBoundToVariable;
923 else if (!SpacesBefore && SpacesAfter)
924 ++CountBoundToType;
925 }
926
Daniel Jasper29f123b2013-02-08 15:28:42 +0000927 if (Tok->Type == TT_TemplateCloser &&
928 Tok->Parent->Type == TT_TemplateCloser &&
929 Tok->FormatTok.WhiteSpaceLength == 0)
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000930 HasCpp03IncompatibleFormat = true;
931 Tok = &Tok->Children[0];
932 }
933 }
934 if (Style.DerivePointerBinding) {
935 if (CountBoundToType > CountBoundToVariable)
936 Style.PointerBindsToType = true;
937 else if (CountBoundToType < CountBoundToVariable)
938 Style.PointerBindsToType = false;
939 }
940 if (Style.Standard == FormatStyle::LS_Auto) {
941 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
942 : FormatStyle::LS_Cpp03;
943 }
944 }
945
Daniel Jasperbac016b2012-12-03 18:12:45 +0000946 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000947 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +0000948 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000949 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +0000950 unsigned PreviousEndOfLineColumn = 0;
Nico Weberc2e6d2a2013-02-11 15:32:15 +0000951 TokenAnnotator Annotator(Style, SourceMgr, Lex,
952 Tokens.getIdentTable().get("in"));
Daniel Jasper995e8202013-01-14 13:08:07 +0000953 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Daniel Jasper8ff690a2013-02-06 14:22:40 +0000954 Annotator.annotate(AnnotatedLines[i]);
955 }
956 deriveLocalStyle();
957 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
958 Annotator.calculateFormattingInformation(AnnotatedLines[i]);
Daniel Jasper995e8202013-01-14 13:08:07 +0000959 }
Manuel Klimek547d5db2013-02-08 17:38:27 +0000960 std::vector<int> IndentForLevel;
Daniel Jasper995e8202013-01-14 13:08:07 +0000961 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
962 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000963 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +0000964 const AnnotatedLine &TheLine = *I;
Manuel Klimek547d5db2013-02-08 17:38:27 +0000965 int Offset = GetIndentOffset(TheLine.First);
966 while (IndentForLevel.size() <= TheLine.Level)
967 IndentForLevel.push_back(-1);
968 IndentForLevel.resize(TheLine.Level + 1);
Daniel Jasper995e8202013-01-14 13:08:07 +0000969 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Manuel Klimek547d5db2013-02-08 17:38:27 +0000970 unsigned LevelIndent = GetIndent(IndentForLevel, TheLine.Level);
971 unsigned Indent = LevelIndent;
972 if (static_cast<int>(Indent) + Offset >= 0)
973 Indent += Offset;
974 if (!TheLine.First.FormatTok.WhiteSpaceStart.isValid() ||
975 StructuralError) {
976 Indent = LevelIndent = SourceMgr.getSpellingColumnNumber(
977 TheLine.First.FormatTok.Tok.getLocation()) - 1;
978 } else {
979 formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective,
980 PreviousEndOfLineColumn);
981 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000982 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +0000983 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000984 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +0000985 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000986 PreviousEndOfLineColumn = Formatter.format();
Manuel Klimek547d5db2013-02-08 17:38:27 +0000987 IndentForLevel[TheLine.Level] = LevelIndent;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000988 } else {
989 // If we did not reformat this unwrapped line, the column at the end of
990 // the last token is unchanged - thus, we can calculate the end of the
Manuel Klimek547d5db2013-02-08 17:38:27 +0000991 // last token.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +0000992 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +0000993 SourceMgr.getSpellingColumnNumber(
994 TheLine.Last->FormatTok.Tok.getLocation()) +
995 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000996 SourceMgr, Lex.getLangOpts()) - 1;
Daniel Jasper9ece2bb2013-02-12 16:51:23 +0000997 if (TheLine.First.FormatTok.NewlinesBefore > 0 ||
998 TheLine.First.FormatTok.IsFirst) {
999 unsigned Indent = SourceMgr.getSpellingColumnNumber(
1000 TheLine.First.FormatTok.Tok.getLocation()) - 1;
1001 unsigned LevelIndent = Indent;
1002 if (static_cast<int>(LevelIndent) - Offset >= 0)
1003 LevelIndent -= Offset;
1004 IndentForLevel[TheLine.Level] = LevelIndent;
1005 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001006 }
1007 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001008 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001009 }
1010
1011private:
Manuel Klimek547d5db2013-02-08 17:38:27 +00001012 /// \brief Get the indent of \p Level from \p IndentForLevel.
1013 ///
1014 /// \p IndentForLevel must contain the indent for the level \c l
1015 /// at \p IndentForLevel[l], or a value < 0 if the indent for
1016 /// that level is unknown.
1017 unsigned GetIndent(const std::vector<int> IndentForLevel,
1018 unsigned Level) {
Manuel Klimek547d5db2013-02-08 17:38:27 +00001019 if (IndentForLevel[Level] != -1)
1020 return IndentForLevel[Level];
Manuel Klimek52635ff2013-02-08 19:53:32 +00001021 if (Level == 0)
1022 return 0;
Manuel Klimek547d5db2013-02-08 17:38:27 +00001023 return GetIndent(IndentForLevel, Level - 1) + 2;
1024 }
1025
1026 /// \brief Get the offset of the line relatively to the level.
1027 ///
1028 /// For example, 'public:' labels in classes are offset by 1 or 2
1029 /// characters to the left from their level.
1030 int GetIndentOffset(const AnnotatedToken &RootToken) {
1031 bool IsAccessModifier = false;
1032 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1033 RootToken.is(tok::kw_private))
1034 IsAccessModifier = true;
1035 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1036 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1037 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1038 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1039 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1040 IsAccessModifier = true;
1041
1042 if (IsAccessModifier)
1043 return Style.AccessModifierOffset;
1044 return 0;
1045 }
1046
Manuel Klimek517e8942013-01-11 17:54:10 +00001047 /// \brief Tries to merge lines into one.
1048 ///
1049 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1050 /// if possible; note that \c I will be incremented when lines are merged.
1051 ///
1052 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001053 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001054 std::vector<AnnotatedLine>::iterator &I,
1055 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001056 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1057
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001058 // We can never merge stuff if there are trailing line comments.
1059 if (I->Last->Type == TT_LineComment)
1060 return;
1061
Manuel Klimek517e8942013-01-11 17:54:10 +00001062 // Check whether the UnwrappedLine can be put onto a single line. If
1063 // so, this is bound to be the optimal solution (by definition) and we
1064 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001065 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001066 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001067 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001068
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001069 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001070 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001071
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001072 if (I->Last->is(tok::l_brace)) {
1073 tryMergeSimpleBlock(I, E, Limit);
1074 } else if (I->First.is(tok::kw_if)) {
1075 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001076 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1077 I->First.FormatTok.IsFirst)) {
1078 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001079 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001080 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001081 }
1082
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001083 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1084 std::vector<AnnotatedLine>::iterator E,
1085 unsigned Limit) {
1086 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001087 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1088 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001089 if (I + 2 != E && (I + 2)->InPPDirective &&
1090 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1091 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001092 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001093 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001094 join(Line, *(++I));
1095 }
1096
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001097 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1098 std::vector<AnnotatedLine>::iterator E,
1099 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001100 if (!Style.AllowShortIfStatementsOnASingleLine)
1101 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001102 if ((I + 1)->InPPDirective != I->InPPDirective ||
1103 ((I + 1)->InPPDirective &&
1104 (I + 1)->First.FormatTok.HasUnescapedNewline))
1105 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001106 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001107 if (Line.Last->isNot(tok::r_paren))
1108 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001109 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001110 return;
1111 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1112 return;
1113 // Only inline simple if's (no nested if or else).
1114 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1115 return;
1116 join(Line, *(++I));
1117 }
1118
1119 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001120 std::vector<AnnotatedLine>::iterator E,
1121 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001122 // First, check that the current line allows merging. This is the case if
1123 // we're not in a control flow statement and the last token is an opening
1124 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001125 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001126 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001127 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1128 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1129 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1130 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001131 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001132 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1133 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001134 if (!AllowedTokens)
1135 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001136
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001137 AnnotatedToken *Tok = &(I + 1)->First;
1138 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1139 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
Daniel Jasper729a7432013-02-11 12:36:37 +00001140 Tok->SpacesRequiredBefore = 0;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001141 join(Line, *(I + 1));
1142 I += 1;
1143 } else {
1144 // Check that we still have three lines and they fit into the limit.
1145 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1146 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001147 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001148
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001149 // Second, check that the next line does not contain any braces - if it
1150 // does, readability declines when putting it into a single line.
1151 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1152 return;
1153 do {
1154 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1155 return;
1156 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1157 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001158
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001159 // Last, check that the third line contains a single closing brace.
1160 Tok = &(I + 2)->First;
1161 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1162 Tok->MustBreakBefore)
1163 return;
1164
1165 join(Line, *(I + 1));
1166 join(Line, *(I + 2));
1167 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001168 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001169 }
1170
1171 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1172 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001173 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1174 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001175 }
1176
Daniel Jasper995e8202013-01-14 13:08:07 +00001177 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1178 A.Last->Children.push_back(B.First);
1179 while (!A.Last->Children.empty()) {
1180 A.Last->Children[0].Parent = A.Last;
1181 A.Last = &A.Last->Children[0];
1182 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001183 }
1184
Daniel Jasper995e8202013-01-14 13:08:07 +00001185 bool touchesRanges(const AnnotatedLine &TheLine) {
1186 const FormatToken *First = &TheLine.First.FormatTok;
1187 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001188 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001189 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001190 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001191 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1192 Ranges[i].getBegin()) &&
1193 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1194 LineRange.getBegin()))
1195 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001196 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001197 return false;
1198 }
1199
1200 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001201 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001202 }
1203
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001204 /// \brief Add a new line and the required indent before the first Token
1205 /// of the \c UnwrappedLine if there was no structural parsing error.
1206 /// Returns the indent level of the \c UnwrappedLine.
Manuel Klimek547d5db2013-02-08 17:38:27 +00001207 void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent,
1208 bool InPPDirective, unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001209 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001210
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001211 unsigned Newlines =
1212 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001213 if (Newlines == 0 && !Tok.IsFirst)
1214 Newlines = 1;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001215
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001216 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001217 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001218 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001219 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1220 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001221 }
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001222 }
1223
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001224 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001225 FormatStyle Style;
1226 Lexer &Lex;
1227 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001228 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001229 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001230 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001231 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001232};
1233
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001234tooling::Replacements
1235reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1236 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001237 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001238 OwningPtr<DiagnosticConsumer> DiagPrinter;
1239 if (DiagClient == 0) {
1240 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1241 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1242 DiagClient = DiagPrinter.get();
1243 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001244 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001245 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001246 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001247 Diagnostics.setSourceManager(&SourceMgr);
1248 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001249 return formatter.format();
1250}
1251
Daniel Jasper46ef8522013-01-10 13:08:12 +00001252LangOptions getFormattingLangOpts() {
1253 LangOptions LangOpts;
1254 LangOpts.CPlusPlus = 1;
1255 LangOpts.CPlusPlus11 = 1;
1256 LangOpts.Bool = 1;
1257 LangOpts.ObjC1 = 1;
1258 LangOpts.ObjC2 = 1;
1259 return LangOpts;
1260}
1261
Daniel Jaspercd162382013-01-07 13:26:07 +00001262} // namespace format
1263} // namespace clang