blob: b5e4a7003d2094ff62698ac535c3fedde30feb9e [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 Jasperf7935112012-12-03 18:12:45 +000021#include "clang/Basic/SourceManager.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
24
Daniel Jasper8b529712012-12-04 13:02:32 +000025#include <string>
26
Daniel Jasperf7935112012-12-03 18:12:45 +000027namespace clang {
28namespace format {
29
30// FIXME: Move somewhere sane.
31struct TokenAnnotation {
Daniel Jasperaa1c9202012-12-05 14:57:28 +000032 enum TokenType {
33 TT_Unknown,
34 TT_TemplateOpener,
35 TT_TemplateCloser,
36 TT_BinaryOperator,
37 TT_UnaryOperator,
Daniel Jasper8dd40472012-12-21 09:41:31 +000038 TT_TrailingUnaryOperator,
Daniel Jasperaa1c9202012-12-05 14:57:28 +000039 TT_OverloadedOperator,
40 TT_PointerOrReference,
41 TT_ConditionalExpr,
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000042 TT_CtorInitializerColon,
Daniel Jasperaa1c9202012-12-05 14:57:28 +000043 TT_LineComment,
Fariborz Jahanian68a542a2012-12-20 19:54:13 +000044 TT_BlockComment,
Daniel Jasper050948a52012-12-21 17:58:39 +000045 TT_DirectorySeparator,
Fariborz Jahanian68a542a2012-12-20 19:54:13 +000046 TT_ObjCMethodSpecifier
Daniel Jasperaa1c9202012-12-05 14:57:28 +000047 };
Daniel Jasperf7935112012-12-03 18:12:45 +000048
49 TokenType Type;
50
Daniel Jasperf7935112012-12-03 18:12:45 +000051 bool SpaceRequiredBefore;
52 bool CanBreakBefore;
53 bool MustBreakBefore;
54};
55
56using llvm::MutableArrayRef;
57
58FormatStyle getLLVMStyle() {
59 FormatStyle LLVMStyle;
60 LLVMStyle.ColumnLimit = 80;
61 LLVMStyle.MaxEmptyLinesToKeep = 1;
62 LLVMStyle.PointerAndReferenceBindToType = false;
63 LLVMStyle.AccessModifierOffset = -2;
64 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000065 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000066 return LLVMStyle;
67}
68
69FormatStyle getGoogleStyle() {
70 FormatStyle GoogleStyle;
71 GoogleStyle.ColumnLimit = 80;
72 GoogleStyle.MaxEmptyLinesToKeep = 1;
73 GoogleStyle.PointerAndReferenceBindToType = true;
74 GoogleStyle.AccessModifierOffset = -1;
75 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000076 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000077 return GoogleStyle;
78}
79
80struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000081 unsigned PenaltyIndentLevel;
82};
83
84class UnwrappedLineFormatter {
85public:
86 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
87 const UnwrappedLine &Line,
88 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000089 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +000090 : Style(Style), SourceMgr(SourceMgr), Line(Line),
91 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000092 StructuralError(StructuralError) {
Daniel Jasperf7935112012-12-03 18:12:45 +000093 Parameters.PenaltyIndentLevel = 5;
94 }
95
96 void format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +000097 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +000098 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +000099
100 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000101 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000102 State.Column = Indent;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000103 State.ConsumedTokens = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000104 State.Indent.push_back(Indent + 4);
105 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000106 State.FirstLessLess.push_back(0);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000107 State.ForLoopVariablePos = 0;
108 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000109
110 // The first token has already been indented and thus consumed.
111 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000112
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000113 // Check whether the UnwrappedLine can be put onto a single line. If so,
114 // this is bound to be the optimal solution (by definition) and we don't
115 // need to analyze the entire solution space.
116 unsigned Columns = State.Column;
117 bool FitsOnALine = true;
118 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
119 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
120 Line.Tokens[i].Tok.getLength();
121 // A special case for the colon of a constructor initializer as this only
122 // needs to be put on a new line if the line needs to be split.
123 if (Columns > Style.ColumnLimit ||
124 (Annotations[i].MustBreakBefore &&
125 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
126 FitsOnALine = false;
127 break;
128 }
129 }
130
Daniel Jasperf7935112012-12-03 18:12:45 +0000131 // Start iterating at 1 as we have correctly formatted of Token #0 above.
132 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000133 if (FitsOnALine) {
134 addTokenToState(false, false, State);
135 } else {
136 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
137 unsigned Break = calcPenalty(State, true, NoBreak);
138 addTokenToState(Break < NoBreak, false, State);
139 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000140 }
141 }
142
143private:
144 /// \brief The current state when indenting a unwrapped line.
145 ///
146 /// As the indenting tries different combinations this is copied by value.
147 struct IndentState {
148 /// \brief The number of used columns in the current line.
149 unsigned Column;
150
151 /// \brief The number of tokens already consumed.
152 unsigned ConsumedTokens;
153
154 /// \brief The position to which a specific parenthesis level needs to be
155 /// indented.
156 std::vector<unsigned> Indent;
157
Daniel Jaspere9de2602012-12-06 09:56:08 +0000158 /// \brief The position of the last space on each level.
159 ///
160 /// Used e.g. to break like:
161 /// functionCall(Parameter, otherCall(
162 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000163 std::vector<unsigned> LastSpace;
164
Daniel Jaspere9de2602012-12-06 09:56:08 +0000165 /// \brief The position the first "<<" operator encountered on each level.
166 ///
167 /// Used to align "<<" operators. 0 if no such operator has been encountered
168 /// on a level.
169 std::vector<unsigned> FirstLessLess;
170
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000171 /// \brief The column of the first variable in a for-loop declaration.
172 ///
173 /// Used to align the second variable if necessary.
174 unsigned ForLoopVariablePos;
175
176 /// \brief \c true if this line contains a continued for-loop section.
177 bool LineContainsContinuedForLoopSection;
178
Daniel Jasperf7935112012-12-03 18:12:45 +0000179 /// \brief Comparison operator to be able to used \c IndentState in \c map.
180 bool operator<(const IndentState &Other) const {
181 if (Other.ConsumedTokens != ConsumedTokens)
182 return Other.ConsumedTokens > ConsumedTokens;
183 if (Other.Column != Column)
184 return Other.Column > Column;
185 if (Other.Indent.size() != Indent.size())
186 return Other.Indent.size() > Indent.size();
187 for (int i = 0, e = Indent.size(); i != e; ++i) {
188 if (Other.Indent[i] != Indent[i])
189 return Other.Indent[i] > Indent[i];
190 }
191 if (Other.LastSpace.size() != LastSpace.size())
192 return Other.LastSpace.size() > LastSpace.size();
193 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
194 if (Other.LastSpace[i] != LastSpace[i])
195 return Other.LastSpace[i] > LastSpace[i];
196 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000197 if (Other.FirstLessLess.size() != FirstLessLess.size())
198 return Other.FirstLessLess.size() > FirstLessLess.size();
199 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
200 if (Other.FirstLessLess[i] != FirstLessLess[i])
201 return Other.FirstLessLess[i] > FirstLessLess[i];
202 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000203 if (Other.ForLoopVariablePos != ForLoopVariablePos)
204 return Other.ForLoopVariablePos < ForLoopVariablePos;
205 if (Other.LineContainsContinuedForLoopSection !=
206 LineContainsContinuedForLoopSection)
207 return LineContainsContinuedForLoopSection;
Daniel Jasperf7935112012-12-03 18:12:45 +0000208 return false;
209 }
210 };
211
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000212 /// \brief Appends the next token to \p State and updates information
213 /// necessary for indentation.
214 ///
215 /// Puts the token on the current line if \p Newline is \c true and adds a
216 /// line break and necessary indentation otherwise.
217 ///
218 /// If \p DryRun is \c false, also creates and stores the required
219 /// \c Replacement.
220 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000221 unsigned Index = State.ConsumedTokens;
222 const FormatToken &Current = Line.Tokens[Index];
223 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000224 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000225
226 if (Newline) {
227 if (Current.Tok.is(tok::string_literal) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000228 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000229 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000230 } else if (Current.Tok.is(tok::lessless) &&
231 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000232 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000233 } else if (ParenLevel != 0 &&
234 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
235 Current.Tok.is(tok::period))) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000236 // Indent and extra 4 spaces after '=' as it continues an expression.
237 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000238 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000239 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
240 Previous.Tok.is(tok::comma)) {
241 State.Column = State.ForLoopVariablePos;
242 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000243 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000244 }
245
246 if (Line.Tokens[0].Tok.is(tok::kw_for))
247 State.LineContainsContinuedForLoopSection =
248 Previous.Tok.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000249
Daniel Jasperf7935112012-12-03 18:12:45 +0000250 if (!DryRun)
251 replaceWhitespace(Current, 1, State.Column);
252
Daniel Jasper9b155472012-12-04 10:50:12 +0000253 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperf7935112012-12-03 18:12:45 +0000254 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000255 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
256 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperf7935112012-12-03 18:12:45 +0000257 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000258 } else {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000259 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
260 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
261
Daniel Jasperf7935112012-12-03 18:12:45 +0000262 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
263 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
264 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000265
Daniel Jasperf7935112012-12-03 18:12:45 +0000266 if (!DryRun)
267 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000268
269 if (Previous.Tok.is(tok::l_paren) ||
270 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000271 State.Indent[ParenLevel] = State.Column;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000272
Daniel Jasperf7935112012-12-03 18:12:45 +0000273 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000274 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000275 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000276 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000277 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000278 moveStateToNextToken(State);
279 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000280
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000281 /// \brief Mark the next token as consumed in \p State and modify its stacks
282 /// accordingly.
283 void moveStateToNextToken(IndentState &State) {
284 unsigned Index = State.ConsumedTokens;
285 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000286 unsigned ParenLevel = State.Indent.size() - 1;
287
288 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
289 State.FirstLessLess[ParenLevel] = State.Column;
290
291 State.Column += Current.Tok.getLength();
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000292
293 // If we encounter an opening (, [ or <, we add a level to our stacks to
294 // prepare for the following tokens.
295 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
296 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
297 State.Indent.push_back(4 + State.LastSpace.back());
298 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000299 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000300 }
301
302 // If we encounter a closing ), ] or >, we can remove a level from our
303 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000304 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
305 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000306 State.Indent.pop_back();
307 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000308 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000309 }
310
311 ++State.ConsumedTokens;
312 }
313
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000314 /// \brief Calculate the panelty for splitting after the token at \p Index.
315 unsigned splitPenalty(unsigned Index) {
316 assert(Index < Line.Tokens.size() &&
317 "Tried to calculate penalty for splitting after the last token");
318 const FormatToken &Left = Line.Tokens[Index];
319 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000320
321 // In for-loops, prefer breaking at ',' and ';'.
322 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
323 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
324 return 20;
325
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000326 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 return 0;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000328 if (Left.Tok.is(tok::equal) || Left.Tok.is(tok::l_paren) ||
329 Left.Tok.is(tok::pipepipe) || Left.Tok.is(tok::ampamp))
Daniel Jasperf7935112012-12-03 18:12:45 +0000330 return 2;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000331
332 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
333 return 200;
334
Daniel Jasperf7935112012-12-03 18:12:45 +0000335 return 3;
336 }
337
338 /// \brief Calculate the number of lines needed to format the remaining part
339 /// of the unwrapped line.
340 ///
341 /// Assumes the formatting so far has led to
342 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
343 /// added after the previous token.
344 ///
345 /// \param StopAt is used for optimization. If we can determine that we'll
346 /// definitely need at least \p StopAt additional lines, we already know of a
347 /// better solution.
348 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
349 // We are at the end of the unwrapped line, so we don't need any more lines.
350 if (State.ConsumedTokens >= Line.Tokens.size())
351 return 0;
352
353 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
354 return UINT_MAX;
355 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
356 return UINT_MAX;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
358 State.LineContainsContinuedForLoopSection)
359 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000360
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000361 unsigned CurrentPenalty = 0;
362 if (NewLine) {
363 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000364 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000365 }
366
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000367 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000368
369 // Exceeding column limit is bad.
370 if (State.Column > Style.ColumnLimit)
371 return UINT_MAX;
372
Daniel Jasperf7935112012-12-03 18:12:45 +0000373 if (StopAt <= CurrentPenalty)
374 return UINT_MAX;
375 StopAt -= CurrentPenalty;
376
Daniel Jasperf7935112012-12-03 18:12:45 +0000377 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000378 if (I != Memory.end()) {
379 // If this state has already been examined, we can safely return the
380 // previous result if we
381 // - have not hit the optimatization (and thus returned UINT_MAX) OR
382 // - are now computing for a smaller or equal StopAt.
383 unsigned SavedResult = I->second.first;
384 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000385 if (SavedResult != UINT_MAX)
386 return SavedResult + CurrentPenalty;
387 else if (StopAt <= SavedStopAt)
388 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000389 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000390
391 unsigned NoBreak = calcPenalty(State, false, StopAt);
392 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
393 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000394
395 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
396 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000397 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000398
399 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000400 }
401
402 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
403 /// each \c FormatToken.
404 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
405 unsigned Spaces) {
406 Replaces.insert(tooling::Replacement(
407 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
408 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
409 }
410
411 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000412 /// of the \c UnwrappedLine if there was no structural parsing error.
413 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000414 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000415 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000416 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
417 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
418
419 unsigned Newlines =
420 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
421 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
422 if (Newlines == 0 && Offset != 0)
423 Newlines = 1;
424 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000425 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
426 Token.Tok.is(tok::kw_private)) &&
427 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000428 Indent += Style.AccessModifierOffset;
429 replaceWhitespace(Token, Newlines, Indent);
430 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000431 }
432
433 FormatStyle Style;
434 SourceManager &SourceMgr;
435 const UnwrappedLine &Line;
436 const std::vector<TokenAnnotation> &Annotations;
437 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000438 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000439
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000440 // A map from an indent state to a pair (Result, Used-StopAt).
441 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
442 StateMap Memory;
443
Daniel Jasperf7935112012-12-03 18:12:45 +0000444 OptimizationParameters Parameters;
445};
446
447/// \brief Determines extra information about the tokens comprising an
448/// \c UnwrappedLine.
449class TokenAnnotator {
450public:
451 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
452 SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000453 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000454 }
455
456 /// \brief A parser that gathers additional information about tokens.
457 ///
458 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
459 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
460 /// into template parameter lists.
461 class AnnotatingParser {
462 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000463 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000464 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000465 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000466 }
467
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000468 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000469 while (Index < Tokens.size()) {
470 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper9b155472012-12-04 10:50:12 +0000471 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000472 next();
473 return true;
474 }
475 if (Tokens[Index].Tok.is(tok::r_paren) ||
476 Tokens[Index].Tok.is(tok::r_square))
477 return false;
478 if (Tokens[Index].Tok.is(tok::pipepipe) ||
479 Tokens[Index].Tok.is(tok::ampamp) ||
480 Tokens[Index].Tok.is(tok::question) ||
481 Tokens[Index].Tok.is(tok::colon))
482 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000483 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000484 }
485 return false;
486 }
487
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000488 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000489 while (Index < Tokens.size()) {
490 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000491 next();
492 return true;
493 }
494 if (Tokens[Index].Tok.is(tok::r_square))
495 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000496 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000497 }
498 return false;
499 }
500
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000501 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000502 while (Index < Tokens.size()) {
503 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000504 next();
505 return true;
506 }
507 if (Tokens[Index].Tok.is(tok::r_paren))
508 return false;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000509 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000510 }
511 return false;
512 }
513
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000514 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000515 while (Index < Tokens.size()) {
516 if (Tokens[Index].Tok.is(tok::colon)) {
517 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
518 next();
519 return true;
520 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000521 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 }
523 return false;
524 }
525
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000526 void consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 unsigned CurrentIndex = Index;
528 next();
529 switch (Tokens[CurrentIndex].Tok.getKind()) {
530 case tok::l_paren:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000531 parseParens();
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000532 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
533 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
534 next();
535 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000536 break;
537 case tok::l_square:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000538 parseSquare();
Daniel Jasperf7935112012-12-03 18:12:45 +0000539 break;
540 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000541 if (parseAngle())
Daniel Jasperf7935112012-12-03 18:12:45 +0000542 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
543 else {
544 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
545 Index = CurrentIndex + 1;
546 }
547 break;
548 case tok::greater:
549 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
550 break;
551 case tok::kw_operator:
552 if (!Tokens[Index].Tok.is(tok::l_paren))
553 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
554 next();
555 break;
556 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000557 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000558 break;
559 default:
560 break;
561 }
562 }
563
Daniel Jasper050948a52012-12-21 17:58:39 +0000564 void parseIncludeDirective() {
565 while (Index < Tokens.size()) {
566 if (Tokens[Index].Tok.is(tok::slash))
567 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
568 else if (Tokens[Index].Tok.is(tok::less))
569 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
570 else if (Tokens[Index].Tok.is(tok::greater))
571 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
572 next();
573 }
574 }
575
576 void parsePreprocessorDirective() {
577 next();
578 if (Index >= Tokens.size())
579 return;
580 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
581 case tok::pp_include:
582 parseIncludeDirective();
583 break;
584 default:
585 break;
586 }
587 }
588
Daniel Jasperf7935112012-12-03 18:12:45 +0000589 void parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000590 if (Tokens[Index].Tok.is(tok::hash)) {
591 parsePreprocessorDirective();
592 return;
593 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000594 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000595 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 }
597 }
598
599 void next() {
600 ++Index;
601 }
602
603 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000604 const SmallVector<FormatToken, 16> &Tokens;
605 std::vector<TokenAnnotation> &Annotations;
606 unsigned Index;
607 };
608
609 void annotate() {
610 Annotations.clear();
611 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
612 Annotations.push_back(TokenAnnotation());
613 }
614
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000615 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000616 Parser.parseLine();
617
618 determineTokenTypes();
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000619 bool IsObjCMethodDecl =
Daniel Jasper8dd40472012-12-21 09:41:31 +0000620 (Line.Tokens.size() > 0 &&
621 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperf7935112012-12-03 18:12:45 +0000622 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
623 TokenAnnotation &Annotation = Annotations[i];
624
625 Annotation.CanBreakBefore =
626 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
627
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000628 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
629 Annotation.MustBreakBefore = true;
630 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000631 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
632 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
633 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000634 Annotation.CanBreakBefore = true;
635 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000636 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
637 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
638 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000639 // Don't break this identifier as ':' or identifier
640 // before it will break.
641 Annotation.CanBreakBefore = false;
642 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000643 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000644 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000645 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000646 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000647 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000648 Annotation.SpaceRequiredBefore =
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000649 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
650 (i != e - 1);
651 // Don't break at ':' if identifier before it can beak.
Daniel Jasper8dd40472012-12-21 09:41:31 +0000652 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
653 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000654 Annotation.CanBreakBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000655 } else if (
656 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000657 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000658 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 Annotation.SpaceRequiredBefore = false;
660 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
661 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000662 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
663 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000664 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
665 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000666 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000667 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000668 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 else
670 Annotation.SpaceRequiredBefore = false;
671 } else if (
Daniel Jasper050948a52012-12-21 17:58:39 +0000672 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
673 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
674 Annotation.SpaceRequiredBefore = false;
675 } else if (
Daniel Jasperf7935112012-12-03 18:12:45 +0000676 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
677 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
678 Annotation.SpaceRequiredBefore = true;
679 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000680 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 Line.Tokens[i].Tok.is(tok::l_paren)) {
682 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000683 } else if (Line.Tokens[i].Tok.is(tok::less) &&
684 Line.Tokens[0].Tok.is(tok::hash)) {
685 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000686 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
687 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000688 // Don't space between ')' and <id>
689 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000690 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
691 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000692 // Don't space between ':' and '('
693 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000694 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
695 Annotation.SpaceRequiredBefore = false;
696 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000697 Annotation.SpaceRequiredBefore =
698 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
699 }
700
701 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
702 (Line.Tokens[i].Tok.is(tok::string_literal) &&
703 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
704 Annotation.MustBreakBefore = true;
705 }
706
707 if (Annotation.MustBreakBefore)
708 Annotation.CanBreakBefore = true;
709 }
710 }
711
712 const std::vector<TokenAnnotation> &getAnnotations() {
713 return Annotations;
714 }
715
716private:
717 void determineTokenTypes() {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000718 bool AssignmentEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000719 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
720 TokenAnnotation &Annotation = Annotations[i];
721 const FormatToken &Tok = Line.Tokens[i];
722
Daniel Jasperab7654e2012-12-21 10:20:02 +0000723 if (getBinOpPrecedence(Tok.Tok.getKind(), true, true) == prec::Assignment)
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000724 AssignmentEncountered = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000725
Daniel Jasperab7654e2012-12-21 10:20:02 +0000726 if (Annotation.Type != TokenAnnotation::TT_Unknown)
727 continue;
728
Daniel Jasper8dd40472012-12-21 09:41:31 +0000729 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000730 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000731 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
732 Annotation.Type = determinePlusMinusUsage(i);
733 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
734 Annotation.Type = determineIncrementUsage(i);
735 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000736 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000737 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000739 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
741 Tok.Tok.getLength());
742 if (Data.startswith("//"))
743 Annotation.Type = TokenAnnotation::TT_LineComment;
744 else
745 Annotation.Type = TokenAnnotation::TT_BlockComment;
746 }
747 }
748 }
749
Daniel Jasperf7935112012-12-03 18:12:45 +0000750 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000751 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasperab7654e2012-12-21 10:20:02 +0000752 return getBinOpPrecedence(Tok.Tok.getKind(), true, true) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000753 }
754
Daniel Jasper426702d2012-12-05 07:51:39 +0000755 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000756 bool AssignmentEncountered) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000757 if (Index == Annotations.size())
758 return TokenAnnotation::TT_Unknown;
759
760 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
761 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
762 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
763 return TokenAnnotation::TT_UnaryOperator;
764
765 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper8dd40472012-12-21 09:41:31 +0000766 Line.Tokens[Index + 1].Tok.isLiteral() ||
767 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 return TokenAnnotation::TT_BinaryOperator;
769
Daniel Jasper426702d2012-12-05 07:51:39 +0000770 // It is very unlikely that we are going to find a pointer or reference type
771 // definition on the RHS of an assignment.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000772 if (AssignmentEncountered)
Daniel Jasper426702d2012-12-05 07:51:39 +0000773 return TokenAnnotation::TT_BinaryOperator;
774
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 return TokenAnnotation::TT_PointerOrReference;
776 }
777
Daniel Jasper8dd40472012-12-21 09:41:31 +0000778 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
779 // At the start of the line, +/- specific ObjectiveC method declarations.
780 if (Index == 0)
781 return TokenAnnotation::TT_ObjCMethodSpecifier;
782
783 // Use heuristics to recognize unary operators.
784 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
785 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
786 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
787 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
788 return TokenAnnotation::TT_UnaryOperator;
789
790 // There can't be to consecutive binary operators.
791 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
792 return TokenAnnotation::TT_UnaryOperator;
793
794 // Fall back to marking the token as binary operator.
795 return TokenAnnotation::TT_BinaryOperator;
796 }
797
798 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
799 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
800 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
801 return TokenAnnotation::TT_TrailingUnaryOperator;
802
803 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000804 }
805
806 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000807 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
808 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000809 if (Left.is(tok::kw_template) && Right.is(tok::less))
810 return true;
811 if (Left.is(tok::arrow) || Right.is(tok::arrow))
812 return false;
813 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
814 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000815 if (Left.is(tok::at) && Right.is(tok::identifier))
816 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000817 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
818 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000819 if (Right.is(tok::amp) || Right.is(tok::star))
820 return Left.isLiteral() ||
821 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
822 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 if (Left.is(tok::amp) || Left.is(tok::star))
824 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
825 if (Right.is(tok::star) && Left.is(tok::l_paren))
826 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000827 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
828 Right.is(tok::r_square))
829 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000830 if (Left.is(tok::coloncolon) ||
831 (Right.is(tok::coloncolon) &&
832 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000833 return false;
834 if (Left.is(tok::period) || Right.is(tok::period))
835 return false;
836 if (Left.is(tok::colon) || Right.is(tok::colon))
837 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 if (Left.is(tok::l_paren))
839 return false;
840 if (Left.is(tok::hash))
841 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000842 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000843 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
844 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
845 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
846 Left.isNot(tok::kw_typeof));
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 }
848 return true;
849 }
850
851 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jaspere25509f2012-12-17 11:29:41 +0000852 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
853 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000854 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000855 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
856 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
857 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
858 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
859 Left.Tok.is(tok::l_brace) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
861 }
862
863 const UnwrappedLine &Line;
864 FormatStyle Style;
865 SourceManager &SourceMgr;
866 std::vector<TokenAnnotation> Annotations;
867};
868
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000869class LexerBasedFormatTokenSource : public FormatTokenSource {
870public:
871 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000872 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000873 IdentTable(Lex.getLangOpts()) {
874 Lex.SetKeepWhitespaceMode(true);
875 }
876
877 virtual FormatToken getNextToken() {
878 if (GreaterStashed) {
879 FormatTok.NewlinesBefore = 0;
880 FormatTok.WhiteSpaceStart =
881 FormatTok.Tok.getLocation().getLocWithOffset(1);
882 FormatTok.WhiteSpaceLength = 0;
883 GreaterStashed = false;
884 return FormatTok;
885 }
886
887 FormatTok = FormatToken();
888 Lex.LexFromRawLexer(FormatTok.Tok);
889 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
890
891 // Consume and record whitespace until we find a significant token.
892 while (FormatTok.Tok.is(tok::unknown)) {
893 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
894 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
895
896 if (FormatTok.Tok.is(tok::eof))
897 return FormatTok;
898 Lex.LexFromRawLexer(FormatTok.Tok);
899 }
900
901 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000902 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
903 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000904 FormatTok.Tok.setKind(Info.getTokenID());
905 }
906
907 if (FormatTok.Tok.is(tok::greatergreater)) {
908 FormatTok.Tok.setKind(tok::greater);
909 GreaterStashed = true;
910 }
911
912 return FormatTok;
913 }
914
915private:
916 FormatToken FormatTok;
917 bool GreaterStashed;
918 Lexer &Lex;
919 SourceManager &SourceMgr;
920 IdentifierTable IdentTable;
921
922 /// Returns the text of \c FormatTok.
923 StringRef tokenText(Token &Tok) {
924 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
925 Tok.getLength());
926 }
927};
928
Daniel Jasperf7935112012-12-03 18:12:45 +0000929class Formatter : public UnwrappedLineConsumer {
930public:
931 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
932 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000933 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000934 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000935 }
936
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000937 virtual ~Formatter() {
938 }
939
Daniel Jasperf7935112012-12-03 18:12:45 +0000940 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000941 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
942 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000943 StructuralError = Parser.parse();
944 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
945 E = UnwrappedLines.end();
946 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000947 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +0000948 return Replaces;
949 }
950
951private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000952 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000953 UnwrappedLines.push_back(TheLine);
954 }
955
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000956 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000957 if (TheLine.Tokens.size() == 0)
958 return;
959
960 CharSourceRange LineRange =
961 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
962 TheLine.Tokens.back().Tok.getLocation());
963
964 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
965 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
966 Ranges[i].getBegin()) ||
967 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
968 LineRange.getBegin()))
969 continue;
970
971 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
972 Annotator.annotate();
973 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000974 Annotator.getAnnotations(), Replaces,
975 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +0000976 Formatter.format();
977 return;
978 }
979 }
980
981 FormatStyle Style;
982 Lexer &Lex;
983 SourceManager &SourceMgr;
984 tooling::Replacements Replaces;
985 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000986 std::vector<UnwrappedLine> UnwrappedLines;
987 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000988};
989
990tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
991 SourceManager &SourceMgr,
992 std::vector<CharSourceRange> Ranges) {
993 Formatter formatter(Style, Lex, SourceMgr, Ranges);
994 return formatter.format();
995}
996
997} // namespace format
998} // namespace clang