blob: c08bcf4f5c109a66619c2aac555af846731188ef [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
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 Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperbac016b2012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000031 enum TokenType {
32 TT_Unknown,
33 TT_TemplateOpener,
34 TT_TemplateCloser,
35 TT_BinaryOperator,
36 TT_UnaryOperator,
Daniel Jasper98e6b4a2012-12-21 09:41:31 +000037 TT_TrailingUnaryOperator,
Daniel Jasper33182dd2012-12-05 14:57:28 +000038 TT_OverloadedOperator,
39 TT_PointerOrReference,
40 TT_ConditionalExpr,
Daniel Jasper1321eb52012-12-18 21:05:13 +000041 TT_CtorInitializerColon,
Daniel Jasper33182dd2012-12-05 14:57:28 +000042 TT_LineComment,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000043 TT_BlockComment,
Daniel Jaspercd1a32b2012-12-21 17:58:39 +000044 TT_DirectorySeparator,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000045 TT_ObjCMethodSpecifier
Daniel Jasper33182dd2012-12-05 14:57:28 +000046 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000047
48 TokenType Type;
49
Daniel Jasperbac016b2012-12-03 18:12:45 +000050 bool SpaceRequiredBefore;
51 bool CanBreakBefore;
52 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000053
54 bool ClosesTemplateDeclaration;
Daniel Jasperbac016b2012-12-03 18:12:45 +000055};
56
Daniel Jaspercf225b62012-12-24 13:43:52 +000057static prec::Level getPrecedence(const FormatToken &Tok) {
58 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
59}
60
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000070 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000081 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000082 return GoogleStyle;
83}
84
85struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000086 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +000087 unsigned PenaltyLevelDecrease;
Daniel Jasperbac016b2012-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 Kornienkocff563c2012-12-04 17:27:50 +000095 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000096 : Style(Style), SourceMgr(SourceMgr), Line(Line),
97 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000098 StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +000099 Parameters.PenaltyIndentLevel = 15;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000100 Parameters.PenaltyLevelDecrease = 10;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000101 }
102
103 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000104 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000105 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000106
107 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000108 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000109 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000110 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000111 State.Indent.push_back(Indent + 4);
112 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000113 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000114 State.ForLoopVariablePos = 0;
115 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000116 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000117
118 // The first token has already been indented and thus consumed.
119 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000120
Daniel Jasper1321eb52012-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 Jasperd7610b82012-12-24 16:51:15 +0000128 Line.Tokens[i].Tok.getLength();
Daniel Jasper1321eb52012-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 Jasperbac016b2012-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 Jasper1321eb52012-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 Jasperbac016b2012-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 Jaspera4974cf2012-12-24 16:43:00 +0000162 /// \brief The parenthesis level of the first token on the current line.
163 unsigned StartOfLineLevel;
164
Daniel Jasperbac016b2012-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 Jasper3b5943f2012-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 Jasperbac016b2012-12-03 18:12:45 +0000174 std::vector<unsigned> LastSpace;
175
Daniel Jasper3b5943f2012-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 Jaspera324a0e2012-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 Jasperbac016b2012-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 Jaspera4974cf2012-12-24 16:43:00 +0000196 if (Other.StartOfLineLevel != StartOfLineLevel)
197 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-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 Jasper3b5943f2012-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 Jaspera324a0e2012-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 Jasperbac016b2012-12-03 18:12:45 +0000221 return false;
222 }
223 };
224
Daniel Jasper20409152012-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 Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000237 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000238
239 if (Newline) {
240 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000241 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000242 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000243 } else if (Current.Tok.is(tok::lessless) &&
244 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000245 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-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 Jasper20409152012-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 Jasperbac016b2012-12-03 18:12:45 +0000251 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasperd7610b82012-12-24 16:51:15 +0000252 } else if (
253 Line.Tokens[0].Tok.is(tok::kw_for) && Previous.Tok.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000254 State.Column = State.ForLoopVariablePos;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000255 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
256 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000257 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000258 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000259 }
260
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000261 State.StartOfLineLevel = ParenLevel + 1;
262
Daniel Jaspera324a0e2012-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 Jasper20409152012-12-04 14:54:30 +0000266
Daniel Jasperbac016b2012-12-03 18:12:45 +0000267 if (!DryRun)
268 replaceWhitespace(Current, 1, State.Column);
269
Daniel Jaspera88bb452012-12-04 10:50:12 +0000270 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000271 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000272 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
273 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000274 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000275 } else {
Daniel Jaspera324a0e2012-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 Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000282
Daniel Jasperbac016b2012-12-03 18:12:45 +0000283 if (!DryRun)
284 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000285
Daniel Jaspercf225b62012-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 Jasper20409152012-12-04 14:54:30 +0000290 if (Previous.Tok.is(tok::l_paren) ||
291 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000292 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000293
Daniel Jasperbac016b2012-12-03 18:12:45 +0000294 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000295 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000296 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000297 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000298 }
Daniel Jasper20409152012-12-04 14:54:30 +0000299 moveStateToNextToken(State);
300 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000301
Daniel Jasper20409152012-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 Jasper3b5943f2012-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 Jasper20409152012-12-04 14:54:30 +0000313
Daniel Jaspercf225b62012-12-24 13:43:52 +0000314 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-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 Jaspercf225b62012-12-24 13:43:52 +0000317 Current.Tok.is(tok::l_brace) ||
Daniel Jasper20409152012-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 Jasper3b5943f2012-12-06 09:56:08 +0000321 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000322 }
323
Daniel Jaspercf225b62012-12-24 13:43:52 +0000324 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000325 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000326 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000327 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jaspera88bb452012-12-04 10:50:12 +0000328 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 State.Indent.pop_back();
330 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000331 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000332 }
333
334 ++State.ConsumedTokens;
335 }
336
Daniel Jasper9a0b4942012-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 Jaspera324a0e2012-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 Jasper9a64fb52013-01-02 15:08:56 +0000349 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
350 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000351 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000352 if (Left.Tok.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000353 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000354
Daniel Jaspercf225b62012-12-24 13:43:52 +0000355 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000356 if (Level != prec::Unknown)
357 return Level;
358
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000359 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000360 return 50;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000361
Daniel Jasperbac016b2012-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 Jaspera324a0e2012-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 Jasperbac016b2012-12-03 18:12:45 +0000387
Daniel Jasper33182dd2012-12-05 14:57:28 +0000388 unsigned CurrentPenalty = 0;
389 if (NewLine) {
390 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperd7610b82012-12-24 16:51:15 +0000391 splitPenalty(State.ConsumedTokens - 1);
Daniel Jaspera4974cf2012-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 Jasper33182dd2012-12-05 14:57:28 +0000396 }
397
Daniel Jasper20409152012-12-04 14:54:30 +0000398 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399
400 // Exceeding column limit is bad.
401 if (State.Column > Style.ColumnLimit)
402 return UINT_MAX;
403
Daniel Jasperbac016b2012-12-03 18:12:45 +0000404 if (StopAt <= CurrentPenalty)
405 return UINT_MAX;
406 StopAt -= CurrentPenalty;
407
Daniel Jasperbac016b2012-12-03 18:12:45 +0000408 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-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 Jasper9a0b4942012-12-17 14:34:14 +0000416 if (SavedResult != UINT_MAX)
417 return SavedResult + CurrentPenalty;
418 else if (StopAt <= SavedStopAt)
419 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000420 }
Daniel Jasperbac016b2012-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 Jasper9a0b4942012-12-17 14:34:14 +0000425
426 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
427 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000428 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000429
430 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-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 Kornienko720ffb62012-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 Kornienkocff563c2012-12-04 17:27:50 +0000445 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000446 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-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 Kornienko56e49c52012-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 Kornienkocff563c2012-12-04 17:27:50 +0000459 Indent += Style.AccessModifierOffset;
460 replaceWhitespace(Token, Newlines, Indent);
461 return Indent;
Daniel Jasperbac016b2012-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 Kornienkocff563c2012-12-04 17:27:50 +0000469 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000470
Daniel Jasper33182dd2012-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 Jasperbac016b2012-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 Jasper1321eb52012-12-18 21:05:13 +0000484 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-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 Klimek0be4b362012-12-03 20:55:42 +0000494 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000496 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000497 }
498
Daniel Jasper20409152012-12-04 14:54:30 +0000499 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000500 while (Index < Tokens.size()) {
501 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000502 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000514 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000515 }
516 return false;
517 }
518
Daniel Jasper20409152012-12-04 14:54:30 +0000519 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000520 while (Index < Tokens.size()) {
521 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000522 next();
523 return true;
524 }
525 if (Tokens[Index].Tok.is(tok::r_square))
526 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000527 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000528 }
529 return false;
530 }
531
Daniel Jasper20409152012-12-04 14:54:30 +0000532 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000533 while (Index < Tokens.size()) {
534 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 next();
536 return true;
537 }
538 if (Tokens[Index].Tok.is(tok::r_paren))
539 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000540 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000541 }
542 return false;
543 }
544
Daniel Jasper20409152012-12-04 14:54:30 +0000545 bool parseConditional() {
Daniel Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000552 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000553 }
554 return false;
555 }
556
Daniel Jasper9a64fb52013-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 Jasper20409152012-12-04 14:54:30 +0000570 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000571 unsigned CurrentIndex = Index;
572 next();
573 switch (Tokens[CurrentIndex].Tok.getKind()) {
574 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000575 parseParens();
Daniel Jasper1321eb52012-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 Jasperbac016b2012-12-03 18:12:45 +0000580 break;
581 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000582 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000583 break;
584 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000585 if (parseAngle())
Daniel Jasperbac016b2012-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 Jasperf6aef6a2012-12-24 10:56:04 +0000596 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000597 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-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 Jasperbac016b2012-12-03 18:12:45 +0000609 break;
610 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000611 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000612 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000613 case tok::kw_template:
614 parseTemplateDeclaration();
615 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616 default:
617 break;
618 }
619 }
620
Daniel Jaspercd1a32b2012-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 Weberb23ae0c2012-12-21 18:21:56 +0000639 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000640 parseIncludeDirective();
641 break;
642 default:
643 break;
644 }
645 }
646
Daniel Jasperbac016b2012-12-03 18:12:45 +0000647 void parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000648 if (Tokens[Index].Tok.is(tok::hash)) {
649 parsePreprocessorDirective();
650 return;
651 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000652 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000653 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000654 }
655 }
656
657 void next() {
658 ++Index;
659 }
660
661 private:
Daniel Jasperbac016b2012-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 Klimek0be4b362012-12-03 20:55:42 +0000673 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000674 Parser.parseLine();
675
676 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000677 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000678 (Line.Tokens.size() > 0 &&
679 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000680 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
681 TokenAnnotation &Annotation = Annotations[i];
682
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000683 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000684
Daniel Jasper1321eb52012-12-18 21:05:13 +0000685 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
686 Annotation.MustBreakBefore = true;
687 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000688 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
689 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-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 Jasperf6aef6a2012-12-24 10:56:04 +0000693 } else if (
694 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
695 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-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 Jahanian154120c2012-12-20 19:54:13 +0000699 Annotation.CanBreakBefore = true;
700 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-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 Jahanian154120c2012-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 Jasper98e6b4a2012-12-21 09:41:31 +0000708 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000709 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000710 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000711 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000712 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000713 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-12-24 16:51:15 +0000714 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
715 (i != e - 1);
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000716 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000717 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
718 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000719 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000720 } else if (
721 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000722 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000723 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000724 Annotation.SpaceRequiredBefore = false;
725 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
726 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-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 Jasperbac016b2012-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 Jasper8822d3a2012-12-04 13:02:32 +0000731 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000732 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000733 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 else
735 Annotation.SpaceRequiredBefore = false;
736 } else if (
Daniel Jaspercd1a32b2012-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 Jasperbac016b2012-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 Jaspera88bb452012-12-04 10:50:12 +0000745 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000746 Line.Tokens[i].Tok.is(tok::l_paren)) {
747 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-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 Jasper98e6b4a2012-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 Jahanian154120c2012-12-20 19:54:13 +0000753 // Don't space between ')' and <id>
754 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-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 Jahanian154120c2012-12-20 19:54:13 +0000757 // Don't space between ':' and '('
758 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000759 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
760 Annotation.SpaceRequiredBefore = false;
761 } else {
Daniel Jasperbac016b2012-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 Weber00d5a042012-12-23 01:07:46 +0000783 bool IsRHS = false;
Daniel Jasperbac016b2012-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 Jaspercf225b62012-12-24 13:43:52 +0000788 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000789 IsRHS = true;
790 else if (Tok.Tok.is(tok::kw_return))
791 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000792
Daniel Jasper675d2e32012-12-21 10:20:02 +0000793 if (Annotation.Type != TokenAnnotation::TT_Unknown)
794 continue;
795
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000796 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000797 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-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 Jasperbac016b2012-12-03 18:12:45 +0000803 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000804 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000805 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000806 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-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 Jasperbac016b2012-12-03 18:12:45 +0000817 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000818 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000819 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 }
821
Daniel Jasperd7610b82012-12-24 16:51:15 +0000822 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000823 if (Index == Annotations.size())
824 return TokenAnnotation::TT_Unknown;
825
826 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
827 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
Nico Weber00d5a042012-12-23 01:07:46 +0000828 Line.Tokens[Index - 1].Tok.is(tok::kw_return) ||
Daniel Jasper5d334402013-01-02 08:57:10 +0000829 Line.Tokens[Index - 1].Tok.is(tok::colon) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000830 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
831 return TokenAnnotation::TT_UnaryOperator;
832
833 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000834 Line.Tokens[Index + 1].Tok.isLiteral() ||
835 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000836 return TokenAnnotation::TT_BinaryOperator;
837
Daniel Jasper112fb272012-12-05 07:51:39 +0000838 // It is very unlikely that we are going to find a pointer or reference type
839 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000840 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000841 return TokenAnnotation::TT_BinaryOperator;
842
Daniel Jasperbac016b2012-12-03 18:12:45 +0000843 return TokenAnnotation::TT_PointerOrReference;
844 }
845
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000846 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
847 // At the start of the line, +/- specific ObjectiveC method declarations.
848 if (Index == 0)
849 return TokenAnnotation::TT_ObjCMethodSpecifier;
850
851 // Use heuristics to recognize unary operators.
852 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
853 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
854 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasper1f0754b2013-01-02 15:26:16 +0000855 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
856 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000857 return TokenAnnotation::TT_UnaryOperator;
858
859 // There can't be to consecutive binary operators.
860 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
861 return TokenAnnotation::TT_UnaryOperator;
862
863 // Fall back to marking the token as binary operator.
864 return TokenAnnotation::TT_BinaryOperator;
865 }
866
867 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
868 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
869 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
870 return TokenAnnotation::TT_TrailingUnaryOperator;
871
872 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000873 }
874
875 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000876 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
877 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000878 if (Left.is(tok::kw_template) && Right.is(tok::less))
879 return true;
880 if (Left.is(tok::arrow) || Right.is(tok::arrow))
881 return false;
882 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
883 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000884 if (Left.is(tok::at) && Right.is(tok::identifier))
885 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000886 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
887 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000888 if (Right.is(tok::amp) || Right.is(tok::star))
889 return Left.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000890 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
891 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000892 if (Left.is(tok::amp) || Left.is(tok::star))
893 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
894 if (Right.is(tok::star) && Left.is(tok::l_paren))
895 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000896 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
897 Right.is(tok::r_square))
898 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000899 if (Left.is(tok::coloncolon) ||
900 (Right.is(tok::coloncolon) &&
901 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000902 return false;
903 if (Left.is(tok::period) || Right.is(tok::period))
904 return false;
905 if (Left.is(tok::colon) || Right.is(tok::colon))
906 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000907 if (Left.is(tok::l_paren))
908 return false;
909 if (Left.is(tok::hash))
910 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000911 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000912 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000913 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
914 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
915 Left.isNot(tok::kw_typeof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000916 }
917 return true;
918 }
919
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000920 bool canBreakBefore(unsigned i) {
921 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
922 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
923 return false;
924 }
925 const FormatToken &Left = Line.Tokens[i - 1];
926 const FormatToken &Right = Line.Tokens[i];
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000927 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
928 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000929 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000930 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000931 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
932 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
933 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
934 Left.Tok.is(tok::l_brace) ||
935 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000936 }
937
938 const UnwrappedLine &Line;
939 FormatStyle Style;
940 SourceManager &SourceMgr;
941 std::vector<TokenAnnotation> Annotations;
942};
943
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000944class LexerBasedFormatTokenSource : public FormatTokenSource {
945public:
946 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000947 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000948 IdentTable(Lex.getLangOpts()) {
949 Lex.SetKeepWhitespaceMode(true);
950 }
951
952 virtual FormatToken getNextToken() {
953 if (GreaterStashed) {
954 FormatTok.NewlinesBefore = 0;
955 FormatTok.WhiteSpaceStart =
956 FormatTok.Tok.getLocation().getLocWithOffset(1);
957 FormatTok.WhiteSpaceLength = 0;
958 GreaterStashed = false;
959 return FormatTok;
960 }
961
962 FormatTok = FormatToken();
963 Lex.LexFromRawLexer(FormatTok.Tok);
964 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
965
966 // Consume and record whitespace until we find a significant token.
967 while (FormatTok.Tok.is(tok::unknown)) {
968 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
969 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
970
971 if (FormatTok.Tok.is(tok::eof))
972 return FormatTok;
973 Lex.LexFromRawLexer(FormatTok.Tok);
974 }
975
976 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000977 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
978 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000979 FormatTok.Tok.setKind(Info.getTokenID());
980 }
981
982 if (FormatTok.Tok.is(tok::greatergreater)) {
983 FormatTok.Tok.setKind(tok::greater);
984 GreaterStashed = true;
985 }
986
987 return FormatTok;
988 }
989
990private:
991 FormatToken FormatTok;
992 bool GreaterStashed;
993 Lexer &Lex;
994 SourceManager &SourceMgr;
995 IdentifierTable IdentTable;
996
997 /// Returns the text of \c FormatTok.
998 StringRef tokenText(Token &Tok) {
999 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1000 Tok.getLength());
1001 }
1002};
1003
Daniel Jasperbac016b2012-12-03 18:12:45 +00001004class Formatter : public UnwrappedLineConsumer {
1005public:
1006 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1007 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001008 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001009 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001010 }
1011
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001012 virtual ~Formatter() {
1013 }
1014
Daniel Jasperbac016b2012-12-03 18:12:45 +00001015 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001016 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1017 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001018 StructuralError = Parser.parse();
1019 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1020 E = UnwrappedLines.end();
1021 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001022 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001023 return Replaces;
1024 }
1025
1026private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001027 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001028 UnwrappedLines.push_back(TheLine);
1029 }
1030
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001031 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001032 if (TheLine.Tokens.size() == 0)
1033 return;
1034
1035 CharSourceRange LineRange =
1036 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1037 TheLine.Tokens.back().Tok.getLocation());
1038
1039 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1040 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1041 Ranges[i].getBegin()) ||
1042 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1043 LineRange.getBegin()))
1044 continue;
1045
1046 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1047 Annotator.annotate();
1048 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001049 Annotator.getAnnotations(), Replaces,
1050 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001051 Formatter.format();
1052 return;
1053 }
1054 }
1055
1056 FormatStyle Style;
1057 Lexer &Lex;
1058 SourceManager &SourceMgr;
1059 tooling::Replacements Replaces;
1060 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001061 std::vector<UnwrappedLine> UnwrappedLines;
1062 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001063};
1064
1065tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1066 SourceManager &SourceMgr,
1067 std::vector<CharSourceRange> Ranges) {
1068 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1069 return formatter.format();
1070}
1071
1072} // namespace format
1073} // namespace clang