blob: 54a2771eb99089334576a0b486822fc62a646940 [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) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000240 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000241 if (Current.Tok.is(tok::string_literal) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000242 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000243 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000244 } else if (Current.Tok.is(tok::lessless) &&
245 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000246 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000247 } else if (ParenLevel != 0 &&
248 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
249 Current.Tok.is(tok::period))) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000250 // Indent and extra 4 spaces after '=' as it continues an expression.
251 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000252 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000253 } else if (
254 Line.Tokens[0].Tok.is(tok::kw_for) && Previous.Tok.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000255 State.Column = State.ForLoopVariablePos;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000256 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
257 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000258 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000259 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000260 }
261
Daniel Jasper6d822722012-12-24 16:43:00 +0000262 State.StartOfLineLevel = ParenLevel + 1;
263
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000264 if (Line.Tokens[0].Tok.is(tok::kw_for))
265 State.LineContainsContinuedForLoopSection =
266 Previous.Tok.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000267
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000268 if (!DryRun) {
269 if (!Line.InPPDirective)
270 replaceWhitespace(Current, 1, State.Column);
271 else
272 replacePPWhitespace(Current, 1, State.Column, WhitespaceStartColumn);
273 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000274
Daniel Jasper9b155472012-12-04 10:50:12 +0000275 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000276 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000277 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
278 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperf7935112012-12-03 18:12:45 +0000279 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000280 } else {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000281 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
282 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
283
Daniel Jasperf7935112012-12-03 18:12:45 +0000284 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
285 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
286 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000287
Daniel Jasperf7935112012-12-03 18:12:45 +0000288 if (!DryRun)
289 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000290
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000291 // FIXME: Look into using this alignment at other ParenLevels.
292 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
293 Previous.Tok.is(tok::kw_return)))
294 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000295 if (Previous.Tok.is(tok::l_paren) ||
296 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000297 State.Indent[ParenLevel] = State.Column;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000298
Daniel Jasperf7935112012-12-03 18:12:45 +0000299 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000300 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000301 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000302 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000303 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000304 moveStateToNextToken(State);
305 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000306
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000307 /// \brief Mark the next token as consumed in \p State and modify its stacks
308 /// accordingly.
309 void moveStateToNextToken(IndentState &State) {
310 unsigned Index = State.ConsumedTokens;
311 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000312 unsigned ParenLevel = State.Indent.size() - 1;
313
314 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
315 State.FirstLessLess[ParenLevel] = State.Column;
316
317 State.Column += Current.Tok.getLength();
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000318
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000319 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000320 // prepare for the following tokens.
321 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000322 Current.Tok.is(tok::l_brace) ||
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000323 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
324 State.Indent.push_back(4 + State.LastSpace.back());
325 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000326 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000327 }
328
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000329 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000330 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000331 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000332 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jasper9b155472012-12-04 10:50:12 +0000333 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000334 State.Indent.pop_back();
335 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000336 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000337 }
338
339 ++State.ConsumedTokens;
340 }
341
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000342 /// \brief Calculate the panelty for splitting after the token at \p Index.
343 unsigned splitPenalty(unsigned Index) {
344 assert(Index < Line.Tokens.size() &&
345 "Tried to calculate penalty for splitting after the last token");
346 const FormatToken &Left = Line.Tokens[Index];
347 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000348
349 // In for-loops, prefer breaking at ',' and ';'.
350 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
351 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
352 return 20;
353
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000354 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
355 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000356 return 0;
Daniel Jasperde5c2072012-12-24 00:13:23 +0000357 if (Left.Tok.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000358 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000359
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000360 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jasperde5c2072012-12-24 00:13:23 +0000361 if (Level != prec::Unknown)
362 return Level;
363
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000364 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jasper6d822722012-12-24 16:43:00 +0000365 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000366
Daniel Jasperf7935112012-12-03 18:12:45 +0000367 return 3;
368 }
369
370 /// \brief Calculate the number of lines needed to format the remaining part
371 /// of the unwrapped line.
372 ///
373 /// Assumes the formatting so far has led to
374 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
375 /// added after the previous token.
376 ///
377 /// \param StopAt is used for optimization. If we can determine that we'll
378 /// definitely need at least \p StopAt additional lines, we already know of a
379 /// better solution.
380 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
381 // We are at the end of the unwrapped line, so we don't need any more lines.
382 if (State.ConsumedTokens >= Line.Tokens.size())
383 return 0;
384
385 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
386 return UINT_MAX;
387 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
388 return UINT_MAX;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000389 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
390 State.LineContainsContinuedForLoopSection)
391 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000392
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000393 unsigned CurrentPenalty = 0;
394 if (NewLine) {
395 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000396 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000397 } else {
398 if (State.Indent.size() < State.StartOfLineLevel)
399 CurrentPenalty += Parameters.PenaltyLevelDecrease *
400 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000401 }
402
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000403 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000404
405 // Exceeding column limit is bad.
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000406 if (State.Column > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0))
Daniel Jasperf7935112012-12-03 18:12:45 +0000407 return UINT_MAX;
408
Daniel Jasperf7935112012-12-03 18:12:45 +0000409 if (StopAt <= CurrentPenalty)
410 return UINT_MAX;
411 StopAt -= CurrentPenalty;
412
Daniel Jasperf7935112012-12-03 18:12:45 +0000413 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000414 if (I != Memory.end()) {
415 // If this state has already been examined, we can safely return the
416 // previous result if we
417 // - have not hit the optimatization (and thus returned UINT_MAX) OR
418 // - are now computing for a smaller or equal StopAt.
419 unsigned SavedResult = I->second.first;
420 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000421 if (SavedResult != UINT_MAX)
422 return SavedResult + CurrentPenalty;
423 else if (StopAt <= SavedStopAt)
424 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000425 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000426
427 unsigned NoBreak = calcPenalty(State, false, StopAt);
428 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
429 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000430
431 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
432 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000433 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000434
435 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000436 }
437
438 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
439 /// each \c FormatToken.
440 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
441 unsigned Spaces) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000442 Replaces.insert(tooling::Replacement(
443 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
444 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
445 }
446
447 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
448 /// backslashes to escape newlines inside a preprocessor directive.
449 ///
450 /// This function and \c replaceWhitespace have the same behavior if
451 /// \c Newlines == 0.
452 void replacePPWhitespace(const FormatToken &Tok, unsigned NewLines,
453 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000454 std::string NewLineText;
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000455 if (NewLines > 0) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000456 unsigned Offset =
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000457 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000458 for (unsigned i = 0; i < NewLines; ++i) {
459 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
460 NewLineText += "\\\n";
461 Offset = 0;
462 }
463 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000464 Replaces.insert(tooling::Replacement(
465 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000466 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperf7935112012-12-03 18:12:45 +0000467 }
468
469 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000470 /// of the \c UnwrappedLine if there was no structural parsing error.
471 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000472 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000473 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000474 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
475 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
476
477 unsigned Newlines =
478 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
479 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
480 if (Newlines == 0 && Offset != 0)
481 Newlines = 1;
482 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000483 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
484 Token.Tok.is(tok::kw_private)) &&
485 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000486 Indent += Style.AccessModifierOffset;
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000487 if (!Line.InPPDirective || Token.HasUnescapedNewline)
488 replaceWhitespace(Token, Newlines, Indent);
489 else
490 // FIXME: Figure out how to get the previous end-of-line column.
491 replacePPWhitespace(Token, Newlines, Indent, 0);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000492 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000493 }
494
495 FormatStyle Style;
496 SourceManager &SourceMgr;
497 const UnwrappedLine &Line;
498 const std::vector<TokenAnnotation> &Annotations;
499 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000500 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000501
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000502 // A map from an indent state to a pair (Result, Used-StopAt).
503 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
504 StateMap Memory;
505
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 OptimizationParameters Parameters;
507};
508
509/// \brief Determines extra information about the tokens comprising an
510/// \c UnwrappedLine.
511class TokenAnnotator {
512public:
513 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
514 SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000515 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000516 }
517
518 /// \brief A parser that gathers additional information about tokens.
519 ///
520 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
521 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
522 /// into template parameter lists.
523 class AnnotatingParser {
524 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000525 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000526 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000527 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000528 }
529
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000530 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000531 while (Index < Tokens.size()) {
532 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000533 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000534 next();
535 return true;
536 }
537 if (Tokens[Index].Tok.is(tok::r_paren) ||
538 Tokens[Index].Tok.is(tok::r_square))
539 return false;
540 if (Tokens[Index].Tok.is(tok::pipepipe) ||
541 Tokens[Index].Tok.is(tok::ampamp) ||
542 Tokens[Index].Tok.is(tok::question) ||
543 Tokens[Index].Tok.is(tok::colon))
544 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000545 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000546 }
547 return false;
548 }
549
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000550 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000551 while (Index < Tokens.size()) {
552 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 next();
554 return true;
555 }
556 if (Tokens[Index].Tok.is(tok::r_square))
557 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000558 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 }
560 return false;
561 }
562
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000563 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000564 while (Index < Tokens.size()) {
565 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000566 next();
567 return true;
568 }
569 if (Tokens[Index].Tok.is(tok::r_paren))
570 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 }
573 return false;
574 }
575
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000576 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 while (Index < Tokens.size()) {
578 if (Tokens[Index].Tok.is(tok::colon)) {
579 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
580 next();
581 return true;
582 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000583 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 }
585 return false;
586 }
587
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000588 bool parseTemplateDeclaration() {
589 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
590 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
591 next();
592 if (!parseAngle())
593 return false;
594 Annotations[Index - 1].ClosesTemplateDeclaration = true;
595 parseLine();
596 return true;
597 }
598 return false;
599 }
600
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000601 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000602 unsigned CurrentIndex = Index;
603 next();
604 switch (Tokens[CurrentIndex].Tok.getKind()) {
605 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000606 parseParens();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000607 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
608 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
609 next();
610 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 break;
612 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000614 break;
615 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000616 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000617 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
618 else {
619 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
620 Index = CurrentIndex + 1;
621 }
622 break;
623 case tok::greater:
624 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
625 break;
626 case tok::kw_operator:
Daniel Jasper537a2962012-12-24 10:56:04 +0000627 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000629 next();
630 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
631 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
632 next();
633 }
634 } else {
635 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
636 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
637 next();
638 }
639 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000640 break;
641 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000642 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000643 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000644 case tok::kw_template:
645 parseTemplateDeclaration();
646 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000647 default:
648 break;
649 }
650 }
651
Daniel Jasper050948a52012-12-21 17:58:39 +0000652 void parseIncludeDirective() {
653 while (Index < Tokens.size()) {
654 if (Tokens[Index].Tok.is(tok::slash))
655 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
656 else if (Tokens[Index].Tok.is(tok::less))
657 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
658 else if (Tokens[Index].Tok.is(tok::greater))
659 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
660 next();
661 }
662 }
663
664 void parsePreprocessorDirective() {
665 next();
666 if (Index >= Tokens.size())
667 return;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000668 // It is the responsibility of the UnwrappedLineParser to make sure
669 // this sequence is not produced inside an unwrapped line.
670 assert(Tokens[Index].Tok.getIdentifierInfo() != NULL);
Daniel Jasper050948a52012-12-21 17:58:39 +0000671 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
672 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000673 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000674 parseIncludeDirective();
675 break;
676 default:
677 break;
678 }
679 }
680
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 void parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000682 if (Tokens[Index].Tok.is(tok::hash)) {
683 parsePreprocessorDirective();
684 return;
685 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000686 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000687 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000688 }
689 }
690
691 void next() {
692 ++Index;
693 }
694
695 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000696 const SmallVector<FormatToken, 16> &Tokens;
697 std::vector<TokenAnnotation> &Annotations;
698 unsigned Index;
699 };
700
701 void annotate() {
702 Annotations.clear();
703 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
704 Annotations.push_back(TokenAnnotation());
705 }
706
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000707 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000708 Parser.parseLine();
709
710 determineTokenTypes();
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000711 bool IsObjCMethodDecl =
Daniel Jasper8dd40472012-12-21 09:41:31 +0000712 (Line.Tokens.size() > 0 &&
713 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
715 TokenAnnotation &Annotation = Annotations[i];
716
Daniel Jasperd1926a32013-01-02 08:44:14 +0000717 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperf7935112012-12-03 18:12:45 +0000718
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000719 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
720 Annotation.MustBreakBefore = true;
721 Annotation.SpaceRequiredBefore = true;
Daniel Jasper537a2962012-12-24 10:56:04 +0000722 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
723 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000724 Line.Tokens[i].Tok.is(tok::identifier) ||
725 Line.Tokens[i].Tok.is(tok::kw_new) ||
726 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasper537a2962012-12-24 10:56:04 +0000727 } else if (
728 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
729 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000730 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
731 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
732 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000733 Annotation.CanBreakBefore = true;
734 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000735 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
736 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
737 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000738 // Don't break this identifier as ':' or identifier
739 // before it will break.
740 Annotation.CanBreakBefore = false;
741 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000742 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000743 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000744 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000745 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000746 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000747 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000748 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
749 (i != e - 1);
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000750 // Don't break at ':' if identifier before it can beak.
Daniel Jasper8dd40472012-12-21 09:41:31 +0000751 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
752 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000753 Annotation.CanBreakBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000754 } else if (
755 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000756 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000757 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 Annotation.SpaceRequiredBefore = false;
759 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
760 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000761 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
762 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000763 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
764 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000765 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000766 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000767 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 else
769 Annotation.SpaceRequiredBefore = false;
770 } else if (
Daniel Jasper050948a52012-12-21 17:58:39 +0000771 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
772 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
773 Annotation.SpaceRequiredBefore = false;
774 } else if (
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
776 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
777 Annotation.SpaceRequiredBefore = true;
778 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000779 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 Line.Tokens[i].Tok.is(tok::l_paren)) {
781 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000782 } else if (Line.Tokens[i].Tok.is(tok::less) &&
783 Line.Tokens[0].Tok.is(tok::hash)) {
784 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000785 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
786 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000787 // Don't space between ')' and <id>
788 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000789 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
790 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000791 // Don't space between ':' and '('
792 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000793 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
794 Annotation.SpaceRequiredBefore = false;
795 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000796 Annotation.SpaceRequiredBefore =
797 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
798 }
799
800 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
801 (Line.Tokens[i].Tok.is(tok::string_literal) &&
802 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
803 Annotation.MustBreakBefore = true;
804 }
805
806 if (Annotation.MustBreakBefore)
807 Annotation.CanBreakBefore = true;
808 }
809 }
810
811 const std::vector<TokenAnnotation> &getAnnotations() {
812 return Annotations;
813 }
814
815private:
816 void determineTokenTypes() {
Nico Weber6f372e62012-12-23 01:07:46 +0000817 bool IsRHS = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
819 TokenAnnotation &Annotation = Annotations[i];
820 const FormatToken &Tok = Line.Tokens[i];
821
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000822 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber6f372e62012-12-23 01:07:46 +0000823 IsRHS = true;
824 else if (Tok.Tok.is(tok::kw_return))
825 IsRHS = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000826
Daniel Jasperab7654e2012-12-21 10:20:02 +0000827 if (Annotation.Type != TokenAnnotation::TT_Unknown)
828 continue;
829
Daniel Jasper8dd40472012-12-21 09:41:31 +0000830 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber6f372e62012-12-23 01:07:46 +0000831 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000832 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
833 Annotation.Type = determinePlusMinusUsage(i);
834 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
835 Annotation.Type = determineIncrementUsage(i);
836 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000837 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000838 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000840 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
842 Tok.Tok.getLength());
843 if (Data.startswith("//"))
844 Annotation.Type = TokenAnnotation::TT_LineComment;
845 else
846 Annotation.Type = TokenAnnotation::TT_BlockComment;
847 }
848 }
849 }
850
Daniel Jasperf7935112012-12-03 18:12:45 +0000851 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000852 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000853 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000854 }
855
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000856 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000857 if (Index == 0)
858 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000859 if (Index == Annotations.size())
860 return TokenAnnotation::TT_Unknown;
Daniel Jasper542de162013-01-02 15:46:59 +0000861 const FormatToken &PrevToken = Line.Tokens[Index - 1];
862 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperf7935112012-12-03 18:12:45 +0000863
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000864 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::comma) ||
865 PrevToken.Tok.is(tok::kw_return) || PrevToken.Tok.is(tok::colon) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000866 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
867 return TokenAnnotation::TT_UnaryOperator;
868
Daniel Jasper542de162013-01-02 15:46:59 +0000869 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000870 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
871 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
872 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
873 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperf7935112012-12-03 18:12:45 +0000874 return TokenAnnotation::TT_BinaryOperator;
875
Daniel Jasper542de162013-01-02 15:46:59 +0000876 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
877 NextToken.Tok.is(tok::greater))
878 return TokenAnnotation::TT_PointerOrReference;
879
Daniel Jasper426702d2012-12-05 07:51:39 +0000880 // It is very unlikely that we are going to find a pointer or reference type
881 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000882 if (IsRHS)
Daniel Jasper426702d2012-12-05 07:51:39 +0000883 return TokenAnnotation::TT_BinaryOperator;
884
Daniel Jasperf7935112012-12-03 18:12:45 +0000885 return TokenAnnotation::TT_PointerOrReference;
886 }
887
Daniel Jasper8dd40472012-12-21 09:41:31 +0000888 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
889 // At the start of the line, +/- specific ObjectiveC method declarations.
890 if (Index == 0)
891 return TokenAnnotation::TT_ObjCMethodSpecifier;
892
893 // Use heuristics to recognize unary operators.
894 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
895 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
896 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasperda1c68a2013-01-02 15:26:16 +0000897 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
898 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper8dd40472012-12-21 09:41:31 +0000899 return TokenAnnotation::TT_UnaryOperator;
900
901 // There can't be to consecutive binary operators.
902 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
903 return TokenAnnotation::TT_UnaryOperator;
904
905 // Fall back to marking the token as binary operator.
906 return TokenAnnotation::TT_BinaryOperator;
907 }
908
909 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
910 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
911 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
912 return TokenAnnotation::TT_TrailingUnaryOperator;
913
914 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 }
916
917 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000918 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
919 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 if (Left.is(tok::kw_template) && Right.is(tok::less))
921 return true;
922 if (Left.is(tok::arrow) || Right.is(tok::arrow))
923 return false;
924 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
925 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000926 if (Left.is(tok::at) && Right.is(tok::identifier))
927 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
929 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000930 if (Right.is(tok::amp) || Right.is(tok::star))
931 return Left.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000932 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
933 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000934 if (Left.is(tok::amp) || Left.is(tok::star))
935 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
936 if (Right.is(tok::star) && Left.is(tok::l_paren))
937 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000938 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
939 Right.is(tok::r_square))
940 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000941 if (Left.is(tok::coloncolon) ||
942 (Right.is(tok::coloncolon) &&
943 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000944 return false;
945 if (Left.is(tok::period) || Right.is(tok::period))
946 return false;
947 if (Left.is(tok::colon) || Right.is(tok::colon))
948 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000949 if (Left.is(tok::l_paren))
950 return false;
951 if (Left.is(tok::hash))
952 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000953 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000954 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000955 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
956 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000957 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 }
959 return true;
960 }
961
Daniel Jasperd1926a32013-01-02 08:44:14 +0000962 bool canBreakBefore(unsigned i) {
Daniel Jasper90e51fd2013-01-02 18:30:06 +0000963 if (Annotations[i - 1].ClosesTemplateDeclaration)
964 return true;
Daniel Jasperd1926a32013-01-02 08:44:14 +0000965 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
Daniel Jasper90e51fd2013-01-02 18:30:06 +0000966 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser ||
Daniel Jasperd1926a32013-01-02 08:44:14 +0000967 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
968 return false;
969 }
970 const FormatToken &Left = Line.Tokens[i - 1];
971 const FormatToken &Right = Line.Tokens[i];
Daniel Jaspere25509f2012-12-17 11:29:41 +0000972 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
973 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000974 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000975 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000976 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
977 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
978 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
979 Left.Tok.is(tok::l_brace) ||
980 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 }
982
983 const UnwrappedLine &Line;
984 FormatStyle Style;
985 SourceManager &SourceMgr;
986 std::vector<TokenAnnotation> Annotations;
987};
988
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000989class LexerBasedFormatTokenSource : public FormatTokenSource {
990public:
991 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000992 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000993 IdentTable(Lex.getLangOpts()) {
994 Lex.SetKeepWhitespaceMode(true);
995 }
996
997 virtual FormatToken getNextToken() {
998 if (GreaterStashed) {
999 FormatTok.NewlinesBefore = 0;
1000 FormatTok.WhiteSpaceStart =
1001 FormatTok.Tok.getLocation().getLocWithOffset(1);
1002 FormatTok.WhiteSpaceLength = 0;
1003 GreaterStashed = false;
1004 return FormatTok;
1005 }
1006
1007 FormatTok = FormatToken();
1008 Lex.LexFromRawLexer(FormatTok.Tok);
1009 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
1010
1011 // Consume and record whitespace until we find a significant token.
1012 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001013 StringRef Text = tokenText(FormatTok.Tok);
1014 FormatTok.NewlinesBefore += Text.count('\n');
1015 FormatTok.HasUnescapedNewline =
1016 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001017 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1018
1019 if (FormatTok.Tok.is(tok::eof))
1020 return FormatTok;
1021 Lex.LexFromRawLexer(FormatTok.Tok);
1022 }
1023
1024 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001025 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
1026 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001027 FormatTok.Tok.setKind(Info.getTokenID());
1028 }
1029
1030 if (FormatTok.Tok.is(tok::greatergreater)) {
1031 FormatTok.Tok.setKind(tok::greater);
1032 GreaterStashed = true;
1033 }
1034
1035 return FormatTok;
1036 }
1037
1038private:
1039 FormatToken FormatTok;
1040 bool GreaterStashed;
1041 Lexer &Lex;
1042 SourceManager &SourceMgr;
1043 IdentifierTable IdentTable;
1044
1045 /// Returns the text of \c FormatTok.
1046 StringRef tokenText(Token &Tok) {
1047 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1048 Tok.getLength());
1049 }
1050};
1051
Daniel Jasperf7935112012-12-03 18:12:45 +00001052class Formatter : public UnwrappedLineConsumer {
1053public:
1054 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1055 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001056 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001057 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 }
1059
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001060 virtual ~Formatter() {
1061 }
1062
Daniel Jasperf7935112012-12-03 18:12:45 +00001063 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001064 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1065 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001066 StructuralError = Parser.parse();
1067 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1068 E = UnwrappedLines.end();
1069 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001070 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 return Replaces;
1072 }
1073
1074private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001075 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001076 UnwrappedLines.push_back(TheLine);
1077 }
1078
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001079 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001080 if (TheLine.Tokens.size() == 0)
1081 return;
1082
1083 CharSourceRange LineRange =
1084 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1085 TheLine.Tokens.back().Tok.getLocation());
1086
1087 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1088 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1089 Ranges[i].getBegin()) ||
1090 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1091 LineRange.getBegin()))
1092 continue;
1093
1094 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1095 Annotator.annotate();
1096 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001097 Annotator.getAnnotations(), Replaces,
1098 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +00001099 Formatter.format();
1100 return;
1101 }
1102 }
1103
1104 FormatStyle Style;
1105 Lexer &Lex;
1106 SourceManager &SourceMgr;
1107 tooling::Replacements Replaces;
1108 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001109 std::vector<UnwrappedLine> UnwrappedLines;
1110 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001111};
1112
1113tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1114 SourceManager &SourceMgr,
1115 std::vector<CharSourceRange> Ranges) {
1116 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1117 return formatter.format();
1118}
1119
1120} // namespace format
1121} // namespace clang