blob: 3c337ec06314cb9c50beea53e99ad0450e834540 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperf7935112012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasperaa1c9202012-12-05 14:57:28 +000031 enum TokenType {
32 TT_Unknown,
33 TT_TemplateOpener,
34 TT_TemplateCloser,
35 TT_BinaryOperator,
36 TT_UnaryOperator,
Daniel Jasper8dd40472012-12-21 09:41:31 +000037 TT_TrailingUnaryOperator,
Daniel Jasperaa1c9202012-12-05 14:57:28 +000038 TT_OverloadedOperator,
39 TT_PointerOrReference,
40 TT_ConditionalExpr,
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000041 TT_CtorInitializerColon,
Daniel Jasperaa1c9202012-12-05 14:57:28 +000042 TT_LineComment,
Fariborz Jahanian68a542a2012-12-20 19:54:13 +000043 TT_BlockComment,
Daniel Jasper050948a52012-12-21 17:58:39 +000044 TT_DirectorySeparator,
Fariborz Jahanian68a542a2012-12-20 19:54:13 +000045 TT_ObjCMethodSpecifier
Daniel Jasperaa1c9202012-12-05 14:57:28 +000046 };
Daniel Jasperf7935112012-12-03 18:12:45 +000047
48 TokenType Type;
49
Daniel Jasperf7935112012-12-03 18:12:45 +000050 bool SpaceRequiredBefore;
51 bool CanBreakBefore;
52 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000053
54 bool ClosesTemplateDeclaration;
Daniel Jasperf7935112012-12-03 18:12:45 +000055};
56
Daniel Jasper2eda23e2012-12-24 13:43:52 +000057static prec::Level getPrecedence(const FormatToken &Tok) {
58 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
59}
60
Daniel Jasperf7935112012-12-03 18:12:45 +000061using llvm::MutableArrayRef;
62
63FormatStyle getLLVMStyle() {
64 FormatStyle LLVMStyle;
65 LLVMStyle.ColumnLimit = 80;
66 LLVMStyle.MaxEmptyLinesToKeep = 1;
67 LLVMStyle.PointerAndReferenceBindToType = false;
68 LLVMStyle.AccessModifierOffset = -2;
69 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000070 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000071 return LLVMStyle;
72}
73
74FormatStyle getGoogleStyle() {
75 FormatStyle GoogleStyle;
76 GoogleStyle.ColumnLimit = 80;
77 GoogleStyle.MaxEmptyLinesToKeep = 1;
78 GoogleStyle.PointerAndReferenceBindToType = true;
79 GoogleStyle.AccessModifierOffset = -1;
80 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000081 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000082 return GoogleStyle;
83}
84
85struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000086 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +000087 unsigned PenaltyLevelDecrease;
Daniel Jasperf7935112012-12-03 18:12:45 +000088};
89
90class UnwrappedLineFormatter {
91public:
92 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
93 const UnwrappedLine &Line,
94 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000095 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000096 : Style(Style), SourceMgr(SourceMgr), Line(Line),
97 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000098 StructuralError(StructuralError) {
Daniel Jasperde5c2072012-12-24 00:13:23 +000099 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper6d822722012-12-24 16:43:00 +0000100 Parameters.PenaltyLevelDecrease = 10;
Daniel Jasperf7935112012-12-03 18:12:45 +0000101 }
102
103 void format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000104 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000105 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000106
107 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000108 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000109 State.Column = Indent;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000110 State.ConsumedTokens = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000111 State.Indent.push_back(Indent + 4);
112 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000113 State.FirstLessLess.push_back(0);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000114 State.ForLoopVariablePos = 0;
115 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000116 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000117
118 // The first token has already been indented and thus consumed.
119 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000120
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000121 // Check whether the UnwrappedLine can be put onto a single line. If so,
122 // this is bound to be the optimal solution (by definition) and we don't
123 // need to analyze the entire solution space.
124 unsigned Columns = State.Column;
125 bool FitsOnALine = true;
126 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
127 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000128 Line.Tokens[i].Tok.getLength();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000129 // A special case for the colon of a constructor initializer as this only
130 // needs to be put on a new line if the line needs to be split.
131 if (Columns > Style.ColumnLimit ||
132 (Annotations[i].MustBreakBefore &&
133 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
134 FitsOnALine = false;
135 break;
136 }
137 }
138
Daniel Jasperf7935112012-12-03 18:12:45 +0000139 // Start iterating at 1 as we have correctly formatted of Token #0 above.
140 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000141 if (FitsOnALine) {
142 addTokenToState(false, false, State);
143 } else {
144 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
145 unsigned Break = calcPenalty(State, true, NoBreak);
146 addTokenToState(Break < NoBreak, false, State);
147 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000148 }
149 }
150
151private:
152 /// \brief The current state when indenting a unwrapped line.
153 ///
154 /// As the indenting tries different combinations this is copied by value.
155 struct IndentState {
156 /// \brief The number of used columns in the current line.
157 unsigned Column;
158
159 /// \brief The number of tokens already consumed.
160 unsigned ConsumedTokens;
161
Daniel Jasper6d822722012-12-24 16:43:00 +0000162 /// \brief The parenthesis level of the first token on the current line.
163 unsigned StartOfLineLevel;
164
Daniel Jasperf7935112012-12-03 18:12:45 +0000165 /// \brief The position to which a specific parenthesis level needs to be
166 /// indented.
167 std::vector<unsigned> Indent;
168
Daniel Jaspere9de2602012-12-06 09:56:08 +0000169 /// \brief The position of the last space on each level.
170 ///
171 /// Used e.g. to break like:
172 /// functionCall(Parameter, otherCall(
173 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000174 std::vector<unsigned> LastSpace;
175
Daniel Jaspere9de2602012-12-06 09:56:08 +0000176 /// \brief The position the first "<<" operator encountered on each level.
177 ///
178 /// Used to align "<<" operators. 0 if no such operator has been encountered
179 /// on a level.
180 std::vector<unsigned> FirstLessLess;
181
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000182 /// \brief The column of the first variable in a for-loop declaration.
183 ///
184 /// Used to align the second variable if necessary.
185 unsigned ForLoopVariablePos;
186
187 /// \brief \c true if this line contains a continued for-loop section.
188 bool LineContainsContinuedForLoopSection;
189
Daniel Jasperf7935112012-12-03 18:12:45 +0000190 /// \brief Comparison operator to be able to used \c IndentState in \c map.
191 bool operator<(const IndentState &Other) const {
192 if (Other.ConsumedTokens != ConsumedTokens)
193 return Other.ConsumedTokens > ConsumedTokens;
194 if (Other.Column != Column)
195 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000196 if (Other.StartOfLineLevel != StartOfLineLevel)
197 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000198 if (Other.Indent.size() != Indent.size())
199 return Other.Indent.size() > Indent.size();
200 for (int i = 0, e = Indent.size(); i != e; ++i) {
201 if (Other.Indent[i] != Indent[i])
202 return Other.Indent[i] > Indent[i];
203 }
204 if (Other.LastSpace.size() != LastSpace.size())
205 return Other.LastSpace.size() > LastSpace.size();
206 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
207 if (Other.LastSpace[i] != LastSpace[i])
208 return Other.LastSpace[i] > LastSpace[i];
209 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000210 if (Other.FirstLessLess.size() != FirstLessLess.size())
211 return Other.FirstLessLess.size() > FirstLessLess.size();
212 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
213 if (Other.FirstLessLess[i] != FirstLessLess[i])
214 return Other.FirstLessLess[i] > FirstLessLess[i];
215 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000216 if (Other.ForLoopVariablePos != ForLoopVariablePos)
217 return Other.ForLoopVariablePos < ForLoopVariablePos;
218 if (Other.LineContainsContinuedForLoopSection !=
219 LineContainsContinuedForLoopSection)
220 return LineContainsContinuedForLoopSection;
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 return false;
222 }
223 };
224
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000225 /// \brief Appends the next token to \p State and updates information
226 /// necessary for indentation.
227 ///
228 /// Puts the token on the current line if \p Newline is \c true and adds a
229 /// line break and necessary indentation otherwise.
230 ///
231 /// If \p DryRun is \c false, also creates and stores the required
232 /// \c Replacement.
233 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000234 unsigned Index = State.ConsumedTokens;
235 const FormatToken &Current = Line.Tokens[Index];
236 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000237 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000238
239 if (Newline) {
240 if (Current.Tok.is(tok::string_literal) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000241 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000242 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000243 } else if (Current.Tok.is(tok::lessless) &&
244 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000245 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000246 } else if (ParenLevel != 0 &&
247 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
248 Current.Tok.is(tok::period))) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000249 // Indent and extra 4 spaces after '=' as it continues an expression.
250 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000251 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000252 } else if (
253 Line.Tokens[0].Tok.is(tok::kw_for) && Previous.Tok.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000254 State.Column = State.ForLoopVariablePos;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000255 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
256 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000257 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000258 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000259 }
260
Daniel Jasper6d822722012-12-24 16:43:00 +0000261 State.StartOfLineLevel = ParenLevel + 1;
262
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000263 if (Line.Tokens[0].Tok.is(tok::kw_for))
264 State.LineContainsContinuedForLoopSection =
265 Previous.Tok.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000266
Daniel Jasperf7935112012-12-03 18:12:45 +0000267 if (!DryRun)
268 replaceWhitespace(Current, 1, State.Column);
269
Daniel Jasper9b155472012-12-04 10:50:12 +0000270 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000271 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000272 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
273 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperf7935112012-12-03 18:12:45 +0000274 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000275 } else {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000276 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
277 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
278
Daniel Jasperf7935112012-12-03 18:12:45 +0000279 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
280 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
281 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000282
Daniel Jasperf7935112012-12-03 18:12:45 +0000283 if (!DryRun)
284 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000285
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000286 // FIXME: Look into using this alignment at other ParenLevels.
287 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
288 Previous.Tok.is(tok::kw_return)))
289 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000290 if (Previous.Tok.is(tok::l_paren) ||
291 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000292 State.Indent[ParenLevel] = State.Column;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000293
Daniel Jasperf7935112012-12-03 18:12:45 +0000294 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000295 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000296 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000297 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000298 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000299 moveStateToNextToken(State);
300 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000301
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000302 /// \brief Mark the next token as consumed in \p State and modify its stacks
303 /// accordingly.
304 void moveStateToNextToken(IndentState &State) {
305 unsigned Index = State.ConsumedTokens;
306 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000307 unsigned ParenLevel = State.Indent.size() - 1;
308
309 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
310 State.FirstLessLess[ParenLevel] = State.Column;
311
312 State.Column += Current.Tok.getLength();
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000313
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000314 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000315 // prepare for the following tokens.
316 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000317 Current.Tok.is(tok::l_brace) ||
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000318 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
319 State.Indent.push_back(4 + State.LastSpace.back());
320 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000321 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000322 }
323
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000324 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000325 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000326 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000327 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jasper9b155472012-12-04 10:50:12 +0000328 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000329 State.Indent.pop_back();
330 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000331 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000332 }
333
334 ++State.ConsumedTokens;
335 }
336
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000337 /// \brief Calculate the panelty for splitting after the token at \p Index.
338 unsigned splitPenalty(unsigned Index) {
339 assert(Index < Line.Tokens.size() &&
340 "Tried to calculate penalty for splitting after the last token");
341 const FormatToken &Left = Line.Tokens[Index];
342 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000343
344 // In for-loops, prefer breaking at ',' and ';'.
345 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
346 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
347 return 20;
348
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000349 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
350 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000351 return 0;
Daniel Jasperde5c2072012-12-24 00:13:23 +0000352 if (Left.Tok.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000353 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000354
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000355 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jasperde5c2072012-12-24 00:13:23 +0000356 if (Level != prec::Unknown)
357 return Level;
358
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000359 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jasper6d822722012-12-24 16:43:00 +0000360 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000361
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 return 3;
363 }
364
365 /// \brief Calculate the number of lines needed to format the remaining part
366 /// of the unwrapped line.
367 ///
368 /// Assumes the formatting so far has led to
369 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
370 /// added after the previous token.
371 ///
372 /// \param StopAt is used for optimization. If we can determine that we'll
373 /// definitely need at least \p StopAt additional lines, we already know of a
374 /// better solution.
375 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
376 // We are at the end of the unwrapped line, so we don't need any more lines.
377 if (State.ConsumedTokens >= Line.Tokens.size())
378 return 0;
379
380 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
381 return UINT_MAX;
382 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
383 return UINT_MAX;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000384 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
385 State.LineContainsContinuedForLoopSection)
386 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000387
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000388 unsigned CurrentPenalty = 0;
389 if (NewLine) {
390 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000391 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000392 } else {
393 if (State.Indent.size() < State.StartOfLineLevel)
394 CurrentPenalty += Parameters.PenaltyLevelDecrease *
395 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000396 }
397
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000398 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000399
400 // Exceeding column limit is bad.
401 if (State.Column > Style.ColumnLimit)
402 return UINT_MAX;
403
Daniel Jasperf7935112012-12-03 18:12:45 +0000404 if (StopAt <= CurrentPenalty)
405 return UINT_MAX;
406 StopAt -= CurrentPenalty;
407
Daniel Jasperf7935112012-12-03 18:12:45 +0000408 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000409 if (I != Memory.end()) {
410 // If this state has already been examined, we can safely return the
411 // previous result if we
412 // - have not hit the optimatization (and thus returned UINT_MAX) OR
413 // - are now computing for a smaller or equal StopAt.
414 unsigned SavedResult = I->second.first;
415 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000416 if (SavedResult != UINT_MAX)
417 return SavedResult + CurrentPenalty;
418 else if (StopAt <= SavedStopAt)
419 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000420 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000421
422 unsigned NoBreak = calcPenalty(State, false, StopAt);
423 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
424 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000425
426 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
427 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000428 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000429
430 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000431 }
432
433 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
434 /// each \c FormatToken.
435 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
436 unsigned Spaces) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000437 std::string NewLineText;
438 if (!Line.InPPDirective) {
439 NewLineText = std::string(NewLines, '\n');
440 } else if (NewLines > 0) {
441 unsigned Offset =
442 SourceMgr.getSpellingColumnNumber(Tok.WhiteSpaceStart) - 1;
443 for (unsigned i = 0; i < NewLines; ++i) {
444 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
445 NewLineText += "\\\n";
446 Offset = 0;
447 }
448 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000449 Replaces.insert(tooling::Replacement(
450 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000451 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperf7935112012-12-03 18:12:45 +0000452 }
453
454 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000455 /// of the \c UnwrappedLine if there was no structural parsing error.
456 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000457 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000458 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000459 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
460 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
461
462 unsigned Newlines =
463 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
464 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
465 if (Newlines == 0 && Offset != 0)
466 Newlines = 1;
467 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000468 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
469 Token.Tok.is(tok::kw_private)) &&
470 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000471 Indent += Style.AccessModifierOffset;
472 replaceWhitespace(Token, Newlines, Indent);
473 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000474 }
475
476 FormatStyle Style;
477 SourceManager &SourceMgr;
478 const UnwrappedLine &Line;
479 const std::vector<TokenAnnotation> &Annotations;
480 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000481 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000482
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000483 // A map from an indent state to a pair (Result, Used-StopAt).
484 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
485 StateMap Memory;
486
Daniel Jasperf7935112012-12-03 18:12:45 +0000487 OptimizationParameters Parameters;
488};
489
490/// \brief Determines extra information about the tokens comprising an
491/// \c UnwrappedLine.
492class TokenAnnotator {
493public:
494 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
495 SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000496 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000497 }
498
499 /// \brief A parser that gathers additional information about tokens.
500 ///
501 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
502 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
503 /// into template parameter lists.
504 class AnnotatingParser {
505 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000506 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000507 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000508 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000509 }
510
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000511 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000512 while (Index < Tokens.size()) {
513 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000514 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000515 next();
516 return true;
517 }
518 if (Tokens[Index].Tok.is(tok::r_paren) ||
519 Tokens[Index].Tok.is(tok::r_square))
520 return false;
521 if (Tokens[Index].Tok.is(tok::pipepipe) ||
522 Tokens[Index].Tok.is(tok::ampamp) ||
523 Tokens[Index].Tok.is(tok::question) ||
524 Tokens[Index].Tok.is(tok::colon))
525 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000526 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 }
528 return false;
529 }
530
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000531 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000532 while (Index < Tokens.size()) {
533 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000534 next();
535 return true;
536 }
537 if (Tokens[Index].Tok.is(tok::r_square))
538 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000539 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000540 }
541 return false;
542 }
543
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000544 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000545 while (Index < Tokens.size()) {
546 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000547 next();
548 return true;
549 }
550 if (Tokens[Index].Tok.is(tok::r_paren))
551 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000552 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 }
554 return false;
555 }
556
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 while (Index < Tokens.size()) {
559 if (Tokens[Index].Tok.is(tok::colon)) {
560 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
561 next();
562 return true;
563 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000564 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 }
566 return false;
567 }
568
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000569 bool parseTemplateDeclaration() {
570 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
571 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
572 next();
573 if (!parseAngle())
574 return false;
575 Annotations[Index - 1].ClosesTemplateDeclaration = true;
576 parseLine();
577 return true;
578 }
579 return false;
580 }
581
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000582 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 unsigned CurrentIndex = Index;
584 next();
585 switch (Tokens[CurrentIndex].Tok.getKind()) {
586 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000587 parseParens();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000588 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
589 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
590 next();
591 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 break;
593 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000594 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 break;
596 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000597 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
599 else {
600 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
601 Index = CurrentIndex + 1;
602 }
603 break;
604 case tok::greater:
605 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
606 break;
607 case tok::kw_operator:
Daniel Jasper537a2962012-12-24 10:56:04 +0000608 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000609 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000610 next();
611 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
612 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
613 next();
614 }
615 } else {
616 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
617 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
618 next();
619 }
620 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000621 break;
622 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000623 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000624 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000625 case tok::kw_template:
626 parseTemplateDeclaration();
627 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 default:
629 break;
630 }
631 }
632
Daniel Jasper050948a52012-12-21 17:58:39 +0000633 void parseIncludeDirective() {
634 while (Index < Tokens.size()) {
635 if (Tokens[Index].Tok.is(tok::slash))
636 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
637 else if (Tokens[Index].Tok.is(tok::less))
638 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
639 else if (Tokens[Index].Tok.is(tok::greater))
640 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
641 next();
642 }
643 }
644
645 void parsePreprocessorDirective() {
646 next();
647 if (Index >= Tokens.size())
648 return;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000649 // It is the responsibility of the UnwrappedLineParser to make sure
650 // this sequence is not produced inside an unwrapped line.
651 assert(Tokens[Index].Tok.getIdentifierInfo() != NULL);
Daniel Jasper050948a52012-12-21 17:58:39 +0000652 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
653 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000654 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000655 parseIncludeDirective();
656 break;
657 default:
658 break;
659 }
660 }
661
Daniel Jasperf7935112012-12-03 18:12:45 +0000662 void parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000663 if (Tokens[Index].Tok.is(tok::hash)) {
664 parsePreprocessorDirective();
665 return;
666 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000667 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000668 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 }
670 }
671
672 void next() {
673 ++Index;
674 }
675
676 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000677 const SmallVector<FormatToken, 16> &Tokens;
678 std::vector<TokenAnnotation> &Annotations;
679 unsigned Index;
680 };
681
682 void annotate() {
683 Annotations.clear();
684 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
685 Annotations.push_back(TokenAnnotation());
686 }
687
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000688 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000689 Parser.parseLine();
690
691 determineTokenTypes();
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000692 bool IsObjCMethodDecl =
Daniel Jasper8dd40472012-12-21 09:41:31 +0000693 (Line.Tokens.size() > 0 &&
694 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperf7935112012-12-03 18:12:45 +0000695 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
696 TokenAnnotation &Annotation = Annotations[i];
697
Daniel Jasperd1926a32013-01-02 08:44:14 +0000698 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperf7935112012-12-03 18:12:45 +0000699
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000700 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
701 Annotation.MustBreakBefore = true;
702 Annotation.SpaceRequiredBefore = true;
Daniel Jasper537a2962012-12-24 10:56:04 +0000703 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
704 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000705 Line.Tokens[i].Tok.is(tok::identifier) ||
706 Line.Tokens[i].Tok.is(tok::kw_new) ||
707 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasper537a2962012-12-24 10:56:04 +0000708 } else if (
709 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
710 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000711 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
712 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
713 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000714 Annotation.CanBreakBefore = true;
715 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000716 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
717 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
718 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000719 // Don't break this identifier as ':' or identifier
720 // before it will break.
721 Annotation.CanBreakBefore = false;
722 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000723 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000724 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000725 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000726 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000727 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000728 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000729 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
730 (i != e - 1);
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000731 // Don't break at ':' if identifier before it can beak.
Daniel Jasper8dd40472012-12-21 09:41:31 +0000732 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
733 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000734 Annotation.CanBreakBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000735 } else if (
736 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000737 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000738 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 Annotation.SpaceRequiredBefore = false;
740 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
741 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000742 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
743 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000744 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
745 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000746 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000747 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000748 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000749 else
750 Annotation.SpaceRequiredBefore = false;
751 } else if (
Daniel Jasper050948a52012-12-21 17:58:39 +0000752 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
753 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
754 Annotation.SpaceRequiredBefore = false;
755 } else if (
Daniel Jasperf7935112012-12-03 18:12:45 +0000756 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
757 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
758 Annotation.SpaceRequiredBefore = true;
759 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000760 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000761 Line.Tokens[i].Tok.is(tok::l_paren)) {
762 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000763 } else if (Line.Tokens[i].Tok.is(tok::less) &&
764 Line.Tokens[0].Tok.is(tok::hash)) {
765 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000766 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
767 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000768 // Don't space between ')' and <id>
769 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000770 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
771 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000772 // Don't space between ':' and '('
773 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000774 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
775 Annotation.SpaceRequiredBefore = false;
776 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000777 Annotation.SpaceRequiredBefore =
778 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
779 }
780
781 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
782 (Line.Tokens[i].Tok.is(tok::string_literal) &&
783 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
784 Annotation.MustBreakBefore = true;
785 }
786
787 if (Annotation.MustBreakBefore)
788 Annotation.CanBreakBefore = true;
789 }
790 }
791
792 const std::vector<TokenAnnotation> &getAnnotations() {
793 return Annotations;
794 }
795
796private:
797 void determineTokenTypes() {
Nico Weber6f372e62012-12-23 01:07:46 +0000798 bool IsRHS = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000799 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
800 TokenAnnotation &Annotation = Annotations[i];
801 const FormatToken &Tok = Line.Tokens[i];
802
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000803 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber6f372e62012-12-23 01:07:46 +0000804 IsRHS = true;
805 else if (Tok.Tok.is(tok::kw_return))
806 IsRHS = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000807
Daniel Jasperab7654e2012-12-21 10:20:02 +0000808 if (Annotation.Type != TokenAnnotation::TT_Unknown)
809 continue;
810
Daniel Jasper8dd40472012-12-21 09:41:31 +0000811 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber6f372e62012-12-23 01:07:46 +0000812 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000813 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
814 Annotation.Type = determinePlusMinusUsage(i);
815 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
816 Annotation.Type = determineIncrementUsage(i);
817 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000819 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000820 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000821 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000822 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
823 Tok.Tok.getLength());
824 if (Data.startswith("//"))
825 Annotation.Type = TokenAnnotation::TT_LineComment;
826 else
827 Annotation.Type = TokenAnnotation::TT_BlockComment;
828 }
829 }
830 }
831
Daniel Jasperf7935112012-12-03 18:12:45 +0000832 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000833 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000834 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000835 }
836
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000837 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000838 if (Index == 0)
839 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 if (Index == Annotations.size())
841 return TokenAnnotation::TT_Unknown;
Daniel Jasper542de162013-01-02 15:46:59 +0000842 const FormatToken &PrevToken = Line.Tokens[Index - 1];
843 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperf7935112012-12-03 18:12:45 +0000844
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000845 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::comma) ||
846 PrevToken.Tok.is(tok::kw_return) || PrevToken.Tok.is(tok::colon) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
848 return TokenAnnotation::TT_UnaryOperator;
849
Daniel Jasper542de162013-01-02 15:46:59 +0000850 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000851 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
852 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
853 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
854 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperf7935112012-12-03 18:12:45 +0000855 return TokenAnnotation::TT_BinaryOperator;
856
Daniel Jasper542de162013-01-02 15:46:59 +0000857 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
858 NextToken.Tok.is(tok::greater))
859 return TokenAnnotation::TT_PointerOrReference;
860
Daniel Jasper426702d2012-12-05 07:51:39 +0000861 // It is very unlikely that we are going to find a pointer or reference type
862 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000863 if (IsRHS)
Daniel Jasper426702d2012-12-05 07:51:39 +0000864 return TokenAnnotation::TT_BinaryOperator;
865
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 return TokenAnnotation::TT_PointerOrReference;
867 }
868
Daniel Jasper8dd40472012-12-21 09:41:31 +0000869 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
870 // At the start of the line, +/- specific ObjectiveC method declarations.
871 if (Index == 0)
872 return TokenAnnotation::TT_ObjCMethodSpecifier;
873
874 // Use heuristics to recognize unary operators.
875 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
876 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
877 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasperda1c68a2013-01-02 15:26:16 +0000878 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
879 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper8dd40472012-12-21 09:41:31 +0000880 return TokenAnnotation::TT_UnaryOperator;
881
882 // There can't be to consecutive binary operators.
883 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
884 return TokenAnnotation::TT_UnaryOperator;
885
886 // Fall back to marking the token as binary operator.
887 return TokenAnnotation::TT_BinaryOperator;
888 }
889
890 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
891 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
892 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
893 return TokenAnnotation::TT_TrailingUnaryOperator;
894
895 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000896 }
897
898 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000899 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
900 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000901 if (Left.is(tok::kw_template) && Right.is(tok::less))
902 return true;
903 if (Left.is(tok::arrow) || Right.is(tok::arrow))
904 return false;
905 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
906 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000907 if (Left.is(tok::at) && Right.is(tok::identifier))
908 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000909 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
910 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000911 if (Right.is(tok::amp) || Right.is(tok::star))
912 return Left.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000913 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
914 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 if (Left.is(tok::amp) || Left.is(tok::star))
916 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
917 if (Right.is(tok::star) && Left.is(tok::l_paren))
918 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000919 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
920 Right.is(tok::r_square))
921 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000922 if (Left.is(tok::coloncolon) ||
923 (Right.is(tok::coloncolon) &&
924 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000925 return false;
926 if (Left.is(tok::period) || Right.is(tok::period))
927 return false;
928 if (Left.is(tok::colon) || Right.is(tok::colon))
929 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000930 if (Left.is(tok::l_paren))
931 return false;
932 if (Left.is(tok::hash))
933 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000934 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000935 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000936 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
937 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000938 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperf7935112012-12-03 18:12:45 +0000939 }
940 return true;
941 }
942
Daniel Jasperd1926a32013-01-02 08:44:14 +0000943 bool canBreakBefore(unsigned i) {
944 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
945 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
946 return false;
947 }
948 const FormatToken &Left = Line.Tokens[i - 1];
949 const FormatToken &Right = Line.Tokens[i];
Daniel Jaspere25509f2012-12-17 11:29:41 +0000950 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
951 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000952 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000953 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000954 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
955 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
956 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
957 Left.Tok.is(tok::l_brace) ||
958 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +0000959 }
960
961 const UnwrappedLine &Line;
962 FormatStyle Style;
963 SourceManager &SourceMgr;
964 std::vector<TokenAnnotation> Annotations;
965};
966
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000967class LexerBasedFormatTokenSource : public FormatTokenSource {
968public:
969 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000970 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000971 IdentTable(Lex.getLangOpts()) {
972 Lex.SetKeepWhitespaceMode(true);
973 }
974
975 virtual FormatToken getNextToken() {
976 if (GreaterStashed) {
977 FormatTok.NewlinesBefore = 0;
978 FormatTok.WhiteSpaceStart =
979 FormatTok.Tok.getLocation().getLocWithOffset(1);
980 FormatTok.WhiteSpaceLength = 0;
981 GreaterStashed = false;
982 return FormatTok;
983 }
984
985 FormatTok = FormatToken();
986 Lex.LexFromRawLexer(FormatTok.Tok);
987 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
988
989 // Consume and record whitespace until we find a significant token.
990 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000991 StringRef Text = tokenText(FormatTok.Tok);
992 FormatTok.NewlinesBefore += Text.count('\n');
993 FormatTok.HasUnescapedNewline =
994 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000995 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
996
997 if (FormatTok.Tok.is(tok::eof))
998 return FormatTok;
999 Lex.LexFromRawLexer(FormatTok.Tok);
1000 }
1001
1002 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001003 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
1004 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001005 FormatTok.Tok.setKind(Info.getTokenID());
1006 }
1007
1008 if (FormatTok.Tok.is(tok::greatergreater)) {
1009 FormatTok.Tok.setKind(tok::greater);
1010 GreaterStashed = true;
1011 }
1012
1013 return FormatTok;
1014 }
1015
1016private:
1017 FormatToken FormatTok;
1018 bool GreaterStashed;
1019 Lexer &Lex;
1020 SourceManager &SourceMgr;
1021 IdentifierTable IdentTable;
1022
1023 /// Returns the text of \c FormatTok.
1024 StringRef tokenText(Token &Tok) {
1025 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1026 Tok.getLength());
1027 }
1028};
1029
Daniel Jasperf7935112012-12-03 18:12:45 +00001030class Formatter : public UnwrappedLineConsumer {
1031public:
1032 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1033 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001034 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001035 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 }
1037
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001038 virtual ~Formatter() {
1039 }
1040
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001042 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1043 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001044 StructuralError = Parser.parse();
1045 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1046 E = UnwrappedLines.end();
1047 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001048 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 return Replaces;
1050 }
1051
1052private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001053 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001054 UnwrappedLines.push_back(TheLine);
1055 }
1056
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001057 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 if (TheLine.Tokens.size() == 0)
1059 return;
1060
1061 CharSourceRange LineRange =
1062 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1063 TheLine.Tokens.back().Tok.getLocation());
1064
1065 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1066 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1067 Ranges[i].getBegin()) ||
1068 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1069 LineRange.getBegin()))
1070 continue;
1071
1072 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1073 Annotator.annotate();
1074 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001075 Annotator.getAnnotations(), Replaces,
1076 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +00001077 Formatter.format();
1078 return;
1079 }
1080 }
1081
1082 FormatStyle Style;
1083 Lexer &Lex;
1084 SourceManager &SourceMgr;
1085 tooling::Replacements Replaces;
1086 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001087 std::vector<UnwrappedLine> UnwrappedLines;
1088 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001089};
1090
1091tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1092 SourceManager &SourceMgr,
1093 std::vector<CharSourceRange> Ranges) {
1094 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1095 return formatter.format();
1096}
1097
1098} // namespace format
1099} // namespace clang