blob: 60b2f56745f9c0898d14b6fa786835c7c1e5cba8 [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) {
437 Replaces.insert(tooling::Replacement(
438 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
439 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
440 }
441
442 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000443 /// of the \c UnwrappedLine if there was no structural parsing error.
444 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000445 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000446 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000447 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
448 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
449
450 unsigned Newlines =
451 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
452 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
453 if (Newlines == 0 && Offset != 0)
454 Newlines = 1;
455 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000456 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
457 Token.Tok.is(tok::kw_private)) &&
458 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000459 Indent += Style.AccessModifierOffset;
460 replaceWhitespace(Token, Newlines, Indent);
461 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000462 }
463
464 FormatStyle Style;
465 SourceManager &SourceMgr;
466 const UnwrappedLine &Line;
467 const std::vector<TokenAnnotation> &Annotations;
468 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000469 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000470
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000471 // A map from an indent state to a pair (Result, Used-StopAt).
472 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
473 StateMap Memory;
474
Daniel Jasperf7935112012-12-03 18:12:45 +0000475 OptimizationParameters Parameters;
476};
477
478/// \brief Determines extra information about the tokens comprising an
479/// \c UnwrappedLine.
480class TokenAnnotator {
481public:
482 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
483 SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000484 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000485 }
486
487 /// \brief A parser that gathers additional information about tokens.
488 ///
489 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
490 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
491 /// into template parameter lists.
492 class AnnotatingParser {
493 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000494 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000495 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000496 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000497 }
498
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000499 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000500 while (Index < Tokens.size()) {
501 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000502 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000503 next();
504 return true;
505 }
506 if (Tokens[Index].Tok.is(tok::r_paren) ||
507 Tokens[Index].Tok.is(tok::r_square))
508 return false;
509 if (Tokens[Index].Tok.is(tok::pipepipe) ||
510 Tokens[Index].Tok.is(tok::ampamp) ||
511 Tokens[Index].Tok.is(tok::question) ||
512 Tokens[Index].Tok.is(tok::colon))
513 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000514 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000515 }
516 return false;
517 }
518
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000519 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000520 while (Index < Tokens.size()) {
521 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 next();
523 return true;
524 }
525 if (Tokens[Index].Tok.is(tok::r_square))
526 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000527 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000528 }
529 return false;
530 }
531
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000532 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000533 while (Index < Tokens.size()) {
534 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000535 next();
536 return true;
537 }
538 if (Tokens[Index].Tok.is(tok::r_paren))
539 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000540 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000541 }
542 return false;
543 }
544
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000545 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000546 while (Index < Tokens.size()) {
547 if (Tokens[Index].Tok.is(tok::colon)) {
548 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
549 next();
550 return true;
551 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000552 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 }
554 return false;
555 }
556
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000557 bool parseTemplateDeclaration() {
558 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
559 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
560 next();
561 if (!parseAngle())
562 return false;
563 Annotations[Index - 1].ClosesTemplateDeclaration = true;
564 parseLine();
565 return true;
566 }
567 return false;
568 }
569
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000570 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000571 unsigned CurrentIndex = Index;
572 next();
573 switch (Tokens[CurrentIndex].Tok.getKind()) {
574 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000575 parseParens();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000576 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
577 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
578 next();
579 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000580 break;
581 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000582 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000583 break;
584 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000585 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000586 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
587 else {
588 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
589 Index = CurrentIndex + 1;
590 }
591 break;
592 case tok::greater:
593 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
594 break;
595 case tok::kw_operator:
Daniel Jasper537a2962012-12-24 10:56:04 +0000596 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000598 next();
599 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
600 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
601 next();
602 }
603 } else {
604 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
605 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
606 next();
607 }
608 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000609 break;
610 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000611 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000612 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000613 case tok::kw_template:
614 parseTemplateDeclaration();
615 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000616 default:
617 break;
618 }
619 }
620
Daniel Jasper050948a52012-12-21 17:58:39 +0000621 void parseIncludeDirective() {
622 while (Index < Tokens.size()) {
623 if (Tokens[Index].Tok.is(tok::slash))
624 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
625 else if (Tokens[Index].Tok.is(tok::less))
626 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
627 else if (Tokens[Index].Tok.is(tok::greater))
628 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
629 next();
630 }
631 }
632
633 void parsePreprocessorDirective() {
634 next();
635 if (Index >= Tokens.size())
636 return;
637 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
638 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000639 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000640 parseIncludeDirective();
641 break;
642 default:
643 break;
644 }
645 }
646
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 void parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000648 if (Tokens[Index].Tok.is(tok::hash)) {
649 parsePreprocessorDirective();
650 return;
651 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000653 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000654 }
655 }
656
657 void next() {
658 ++Index;
659 }
660
661 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000662 const SmallVector<FormatToken, 16> &Tokens;
663 std::vector<TokenAnnotation> &Annotations;
664 unsigned Index;
665 };
666
667 void annotate() {
668 Annotations.clear();
669 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
670 Annotations.push_back(TokenAnnotation());
671 }
672
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000673 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000674 Parser.parseLine();
675
676 determineTokenTypes();
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000677 bool IsObjCMethodDecl =
Daniel Jasper8dd40472012-12-21 09:41:31 +0000678 (Line.Tokens.size() > 0 &&
679 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperf7935112012-12-03 18:12:45 +0000680 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
681 TokenAnnotation &Annotation = Annotations[i];
682
Daniel Jasperd1926a32013-01-02 08:44:14 +0000683 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperf7935112012-12-03 18:12:45 +0000684
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000685 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
686 Annotation.MustBreakBefore = true;
687 Annotation.SpaceRequiredBefore = true;
Daniel Jasper537a2962012-12-24 10:56:04 +0000688 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
689 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000690 Line.Tokens[i].Tok.is(tok::identifier) ||
691 Line.Tokens[i].Tok.is(tok::kw_new) ||
692 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasper537a2962012-12-24 10:56:04 +0000693 } else if (
694 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
695 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000696 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
697 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
698 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000699 Annotation.CanBreakBefore = true;
700 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000701 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
702 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
703 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000704 // Don't break this identifier as ':' or identifier
705 // before it will break.
706 Annotation.CanBreakBefore = false;
707 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000708 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000709 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000710 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000711 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000712 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000713 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000714 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
715 (i != e - 1);
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000716 // Don't break at ':' if identifier before it can beak.
Daniel Jasper8dd40472012-12-21 09:41:31 +0000717 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
718 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000719 Annotation.CanBreakBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000720 } else if (
721 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000722 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000723 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000724 Annotation.SpaceRequiredBefore = false;
725 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
726 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000727 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
728 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000729 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
730 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000731 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000732 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000733 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000734 else
735 Annotation.SpaceRequiredBefore = false;
736 } else if (
Daniel Jasper050948a52012-12-21 17:58:39 +0000737 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
738 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
739 Annotation.SpaceRequiredBefore = false;
740 } else if (
Daniel Jasperf7935112012-12-03 18:12:45 +0000741 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
742 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
743 Annotation.SpaceRequiredBefore = true;
744 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000745 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000746 Line.Tokens[i].Tok.is(tok::l_paren)) {
747 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000748 } else if (Line.Tokens[i].Tok.is(tok::less) &&
749 Line.Tokens[0].Tok.is(tok::hash)) {
750 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000751 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
752 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000753 // Don't space between ')' and <id>
754 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000755 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
756 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000757 // Don't space between ':' and '('
758 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000759 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
760 Annotation.SpaceRequiredBefore = false;
761 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 Annotation.SpaceRequiredBefore =
763 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
764 }
765
766 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
767 (Line.Tokens[i].Tok.is(tok::string_literal) &&
768 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
769 Annotation.MustBreakBefore = true;
770 }
771
772 if (Annotation.MustBreakBefore)
773 Annotation.CanBreakBefore = true;
774 }
775 }
776
777 const std::vector<TokenAnnotation> &getAnnotations() {
778 return Annotations;
779 }
780
781private:
782 void determineTokenTypes() {
Nico Weber6f372e62012-12-23 01:07:46 +0000783 bool IsRHS = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000784 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
785 TokenAnnotation &Annotation = Annotations[i];
786 const FormatToken &Tok = Line.Tokens[i];
787
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000788 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber6f372e62012-12-23 01:07:46 +0000789 IsRHS = true;
790 else if (Tok.Tok.is(tok::kw_return))
791 IsRHS = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000792
Daniel Jasperab7654e2012-12-21 10:20:02 +0000793 if (Annotation.Type != TokenAnnotation::TT_Unknown)
794 continue;
795
Daniel Jasper8dd40472012-12-21 09:41:31 +0000796 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber6f372e62012-12-23 01:07:46 +0000797 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000798 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
799 Annotation.Type = determinePlusMinusUsage(i);
800 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
801 Annotation.Type = determineIncrementUsage(i);
802 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000804 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000805 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000806 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000807 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
808 Tok.Tok.getLength());
809 if (Data.startswith("//"))
810 Annotation.Type = TokenAnnotation::TT_LineComment;
811 else
812 Annotation.Type = TokenAnnotation::TT_BlockComment;
813 }
814 }
815 }
816
Daniel Jasperf7935112012-12-03 18:12:45 +0000817 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000818 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000819 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000820 }
821
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000822 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 if (Index == Annotations.size())
824 return TokenAnnotation::TT_Unknown;
Daniel Jasper542de162013-01-02 15:46:59 +0000825 const FormatToken &PrevToken = Line.Tokens[Index - 1];
826 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperf7935112012-12-03 18:12:45 +0000827
Daniel Jasper542de162013-01-02 15:46:59 +0000828 if (Index == 0 || PrevToken.Tok.is(tok::l_paren) ||
829 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
830 PrevToken.Tok.is(tok::colon) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000831 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
832 return TokenAnnotation::TT_UnaryOperator;
833
Daniel Jasper542de162013-01-02 15:46:59 +0000834 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
835 NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperf7935112012-12-03 18:12:45 +0000836 return TokenAnnotation::TT_BinaryOperator;
837
Daniel Jasper542de162013-01-02 15:46:59 +0000838 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
839 NextToken.Tok.is(tok::greater))
840 return TokenAnnotation::TT_PointerOrReference;
841
Daniel Jasper426702d2012-12-05 07:51:39 +0000842 // It is very unlikely that we are going to find a pointer or reference type
843 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000844 if (IsRHS)
Daniel Jasper426702d2012-12-05 07:51:39 +0000845 return TokenAnnotation::TT_BinaryOperator;
846
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 return TokenAnnotation::TT_PointerOrReference;
848 }
849
Daniel Jasper8dd40472012-12-21 09:41:31 +0000850 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
851 // At the start of the line, +/- specific ObjectiveC method declarations.
852 if (Index == 0)
853 return TokenAnnotation::TT_ObjCMethodSpecifier;
854
855 // Use heuristics to recognize unary operators.
856 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
857 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
858 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasperda1c68a2013-01-02 15:26:16 +0000859 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
860 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper8dd40472012-12-21 09:41:31 +0000861 return TokenAnnotation::TT_UnaryOperator;
862
863 // There can't be to consecutive binary operators.
864 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
865 return TokenAnnotation::TT_UnaryOperator;
866
867 // Fall back to marking the token as binary operator.
868 return TokenAnnotation::TT_BinaryOperator;
869 }
870
871 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
872 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
873 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
874 return TokenAnnotation::TT_TrailingUnaryOperator;
875
876 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000877 }
878
879 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000880 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
881 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000882 if (Left.is(tok::kw_template) && Right.is(tok::less))
883 return true;
884 if (Left.is(tok::arrow) || Right.is(tok::arrow))
885 return false;
886 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
887 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000888 if (Left.is(tok::at) && Right.is(tok::identifier))
889 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000890 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
891 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000892 if (Right.is(tok::amp) || Right.is(tok::star))
893 return Left.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000894 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
895 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000896 if (Left.is(tok::amp) || Left.is(tok::star))
897 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
898 if (Right.is(tok::star) && Left.is(tok::l_paren))
899 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
901 Right.is(tok::r_square))
902 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000903 if (Left.is(tok::coloncolon) ||
904 (Right.is(tok::coloncolon) &&
905 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000906 return false;
907 if (Left.is(tok::period) || Right.is(tok::period))
908 return false;
909 if (Left.is(tok::colon) || Right.is(tok::colon))
910 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000911 if (Left.is(tok::l_paren))
912 return false;
913 if (Left.is(tok::hash))
914 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000916 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000917 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
918 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
919 Left.isNot(tok::kw_typeof));
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 }
921 return true;
922 }
923
Daniel Jasperd1926a32013-01-02 08:44:14 +0000924 bool canBreakBefore(unsigned i) {
925 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
926 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
927 return false;
928 }
929 const FormatToken &Left = Line.Tokens[i - 1];
930 const FormatToken &Right = Line.Tokens[i];
Daniel Jaspere25509f2012-12-17 11:29:41 +0000931 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
932 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000933 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000934 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000935 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
936 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
937 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
938 Left.Tok.is(tok::l_brace) ||
939 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +0000940 }
941
942 const UnwrappedLine &Line;
943 FormatStyle Style;
944 SourceManager &SourceMgr;
945 std::vector<TokenAnnotation> Annotations;
946};
947
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000948class LexerBasedFormatTokenSource : public FormatTokenSource {
949public:
950 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000951 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000952 IdentTable(Lex.getLangOpts()) {
953 Lex.SetKeepWhitespaceMode(true);
954 }
955
956 virtual FormatToken getNextToken() {
957 if (GreaterStashed) {
958 FormatTok.NewlinesBefore = 0;
959 FormatTok.WhiteSpaceStart =
960 FormatTok.Tok.getLocation().getLocWithOffset(1);
961 FormatTok.WhiteSpaceLength = 0;
962 GreaterStashed = false;
963 return FormatTok;
964 }
965
966 FormatTok = FormatToken();
967 Lex.LexFromRawLexer(FormatTok.Tok);
968 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
969
970 // Consume and record whitespace until we find a significant token.
971 while (FormatTok.Tok.is(tok::unknown)) {
972 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
973 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
974
975 if (FormatTok.Tok.is(tok::eof))
976 return FormatTok;
977 Lex.LexFromRawLexer(FormatTok.Tok);
978 }
979
980 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000981 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
982 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000983 FormatTok.Tok.setKind(Info.getTokenID());
984 }
985
986 if (FormatTok.Tok.is(tok::greatergreater)) {
987 FormatTok.Tok.setKind(tok::greater);
988 GreaterStashed = true;
989 }
990
991 return FormatTok;
992 }
993
994private:
995 FormatToken FormatTok;
996 bool GreaterStashed;
997 Lexer &Lex;
998 SourceManager &SourceMgr;
999 IdentifierTable IdentTable;
1000
1001 /// Returns the text of \c FormatTok.
1002 StringRef tokenText(Token &Tok) {
1003 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1004 Tok.getLength());
1005 }
1006};
1007
Daniel Jasperf7935112012-12-03 18:12:45 +00001008class Formatter : public UnwrappedLineConsumer {
1009public:
1010 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1011 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001012 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001013 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001014 }
1015
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001016 virtual ~Formatter() {
1017 }
1018
Daniel Jasperf7935112012-12-03 18:12:45 +00001019 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001020 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1021 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001022 StructuralError = Parser.parse();
1023 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1024 E = UnwrappedLines.end();
1025 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001026 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +00001027 return Replaces;
1028 }
1029
1030private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001031 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001032 UnwrappedLines.push_back(TheLine);
1033 }
1034
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001035 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001036 if (TheLine.Tokens.size() == 0)
1037 return;
1038
1039 CharSourceRange LineRange =
1040 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1041 TheLine.Tokens.back().Tok.getLocation());
1042
1043 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1044 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1045 Ranges[i].getBegin()) ||
1046 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1047 LineRange.getBegin()))
1048 continue;
1049
1050 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1051 Annotator.annotate();
1052 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001053 Annotator.getAnnotations(), Replaces,
1054 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +00001055 Formatter.format();
1056 return;
1057 }
1058 }
1059
1060 FormatStyle Style;
1061 Lexer &Lex;
1062 SourceManager &SourceMgr;
1063 tooling::Replacements Replaces;
1064 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001065 std::vector<UnwrappedLine> UnwrappedLines;
1066 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001067};
1068
1069tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1070 SourceManager &SourceMgr,
1071 std::vector<CharSourceRange> Ranges) {
1072 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1073 return formatter.format();
1074}
1075
1076} // namespace format
1077} // namespace clang