blob: bb18e9a85151aa863b9522722f0d1bd9d250258b [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:
Nico Weber8f83ee42012-12-21 18:21:56 +0000582 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000583 parseIncludeDirective();
584 break;
585 default:
586 break;
587 }
588 }
589
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 void parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000591 if (Tokens[Index].Tok.is(tok::hash)) {
592 parsePreprocessorDirective();
593 return;
594 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 while (Index < Tokens.size()) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000596 consumeToken();
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 }
598 }
599
600 void next() {
601 ++Index;
602 }
603
604 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000605 const SmallVector<FormatToken, 16> &Tokens;
606 std::vector<TokenAnnotation> &Annotations;
607 unsigned Index;
608 };
609
610 void annotate() {
611 Annotations.clear();
612 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
613 Annotations.push_back(TokenAnnotation());
614 }
615
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000616 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperf7935112012-12-03 18:12:45 +0000617 Parser.parseLine();
618
619 determineTokenTypes();
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000620 bool IsObjCMethodDecl =
Daniel Jasper8dd40472012-12-21 09:41:31 +0000621 (Line.Tokens.size() > 0 &&
622 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
624 TokenAnnotation &Annotation = Annotations[i];
625
626 Annotation.CanBreakBefore =
627 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
628
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000629 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
630 Annotation.MustBreakBefore = true;
631 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000632 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
633 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
634 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000635 Annotation.CanBreakBefore = true;
636 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000637 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
638 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
639 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000640 // Don't break this identifier as ':' or identifier
641 // before it will break.
642 Annotation.CanBreakBefore = false;
643 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000644 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000645 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000646 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000647 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000648 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000649 Annotation.SpaceRequiredBefore =
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000650 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
651 (i != e - 1);
652 // Don't break at ':' if identifier before it can beak.
Daniel Jasper8dd40472012-12-21 09:41:31 +0000653 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
654 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000655 Annotation.CanBreakBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000656 } else if (
657 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000658 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000659 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 Annotation.SpaceRequiredBefore = false;
661 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
662 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000663 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
664 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000665 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
666 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8b529712012-12-04 13:02:32 +0000667 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000668 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000669 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000670 else
671 Annotation.SpaceRequiredBefore = false;
672 } else if (
Daniel Jasper050948a52012-12-21 17:58:39 +0000673 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
674 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
675 Annotation.SpaceRequiredBefore = false;
676 } else if (
Daniel Jasperf7935112012-12-03 18:12:45 +0000677 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
678 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
679 Annotation.SpaceRequiredBefore = true;
680 } else if (
Daniel Jasper9b155472012-12-04 10:50:12 +0000681 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperf7935112012-12-03 18:12:45 +0000682 Line.Tokens[i].Tok.is(tok::l_paren)) {
683 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000684 } else if (Line.Tokens[i].Tok.is(tok::less) &&
685 Line.Tokens[0].Tok.is(tok::hash)) {
686 Annotation.SpaceRequiredBefore = true;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000687 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
688 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000689 // Don't space between ')' and <id>
690 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000691 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
692 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000693 // Don't space between ':' and '('
694 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000695 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
696 Annotation.SpaceRequiredBefore = false;
697 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000698 Annotation.SpaceRequiredBefore =
699 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
700 }
701
702 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
703 (Line.Tokens[i].Tok.is(tok::string_literal) &&
704 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
705 Annotation.MustBreakBefore = true;
706 }
707
708 if (Annotation.MustBreakBefore)
709 Annotation.CanBreakBefore = true;
710 }
711 }
712
713 const std::vector<TokenAnnotation> &getAnnotations() {
714 return Annotations;
715 }
716
717private:
718 void determineTokenTypes() {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000719 bool AssignmentEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000720 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
721 TokenAnnotation &Annotation = Annotations[i];
722 const FormatToken &Tok = Line.Tokens[i];
723
Daniel Jasperab7654e2012-12-21 10:20:02 +0000724 if (getBinOpPrecedence(Tok.Tok.getKind(), true, true) == prec::Assignment)
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000725 AssignmentEncountered = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000726
Daniel Jasperab7654e2012-12-21 10:20:02 +0000727 if (Annotation.Type != TokenAnnotation::TT_Unknown)
728 continue;
729
Daniel Jasper8dd40472012-12-21 09:41:31 +0000730 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000731 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000732 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
733 Annotation.Type = determinePlusMinusUsage(i);
734 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
735 Annotation.Type = determineIncrementUsage(i);
736 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000738 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000740 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000741 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
742 Tok.Tok.getLength());
743 if (Data.startswith("//"))
744 Annotation.Type = TokenAnnotation::TT_LineComment;
745 else
746 Annotation.Type = TokenAnnotation::TT_BlockComment;
747 }
748 }
749 }
750
Daniel Jasperf7935112012-12-03 18:12:45 +0000751 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000752 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasperab7654e2012-12-21 10:20:02 +0000753 return getBinOpPrecedence(Tok.Tok.getKind(), true, true) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000754 }
755
Daniel Jasper426702d2012-12-05 07:51:39 +0000756 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000757 bool AssignmentEncountered) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 if (Index == Annotations.size())
759 return TokenAnnotation::TT_Unknown;
760
761 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
762 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
763 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
764 return TokenAnnotation::TT_UnaryOperator;
765
766 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper8dd40472012-12-21 09:41:31 +0000767 Line.Tokens[Index + 1].Tok.isLiteral() ||
768 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperf7935112012-12-03 18:12:45 +0000769 return TokenAnnotation::TT_BinaryOperator;
770
Daniel Jasper426702d2012-12-05 07:51:39 +0000771 // It is very unlikely that we are going to find a pointer or reference type
772 // definition on the RHS of an assignment.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000773 if (AssignmentEncountered)
Daniel Jasper426702d2012-12-05 07:51:39 +0000774 return TokenAnnotation::TT_BinaryOperator;
775
Daniel Jasperf7935112012-12-03 18:12:45 +0000776 return TokenAnnotation::TT_PointerOrReference;
777 }
778
Daniel Jasper8dd40472012-12-21 09:41:31 +0000779 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
780 // At the start of the line, +/- specific ObjectiveC method declarations.
781 if (Index == 0)
782 return TokenAnnotation::TT_ObjCMethodSpecifier;
783
784 // Use heuristics to recognize unary operators.
785 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
786 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
787 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
788 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
789 return TokenAnnotation::TT_UnaryOperator;
790
791 // There can't be to consecutive binary operators.
792 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
793 return TokenAnnotation::TT_UnaryOperator;
794
795 // Fall back to marking the token as binary operator.
796 return TokenAnnotation::TT_BinaryOperator;
797 }
798
799 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
800 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
801 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
802 return TokenAnnotation::TT_TrailingUnaryOperator;
803
804 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000805 }
806
807 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000808 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
809 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 if (Left.is(tok::kw_template) && Right.is(tok::less))
811 return true;
812 if (Left.is(tok::arrow) || Right.is(tok::arrow))
813 return false;
814 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
815 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000816 if (Left.is(tok::at) && Right.is(tok::identifier))
817 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
819 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000820 if (Right.is(tok::amp) || Right.is(tok::star))
821 return Left.isLiteral() ||
822 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
823 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000824 if (Left.is(tok::amp) || Left.is(tok::star))
825 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
826 if (Right.is(tok::star) && Left.is(tok::l_paren))
827 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000828 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
829 Right.is(tok::r_square))
830 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000831 if (Left.is(tok::coloncolon) ||
832 (Right.is(tok::coloncolon) &&
833 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000834 return false;
835 if (Left.is(tok::period) || Right.is(tok::period))
836 return false;
837 if (Left.is(tok::colon) || Right.is(tok::colon))
838 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 if (Left.is(tok::l_paren))
840 return false;
841 if (Left.is(tok::hash))
842 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000843 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000844 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
845 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
846 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
847 Left.isNot(tok::kw_typeof));
Daniel Jasperf7935112012-12-03 18:12:45 +0000848 }
849 return true;
850 }
851
852 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jaspere25509f2012-12-17 11:29:41 +0000853 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
854 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +0000855 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000856 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
857 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
858 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
859 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
860 Left.Tok.is(tok::l_brace) ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000861 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
862 }
863
864 const UnwrappedLine &Line;
865 FormatStyle Style;
866 SourceManager &SourceMgr;
867 std::vector<TokenAnnotation> Annotations;
868};
869
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000870class LexerBasedFormatTokenSource : public FormatTokenSource {
871public:
872 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000873 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000874 IdentTable(Lex.getLangOpts()) {
875 Lex.SetKeepWhitespaceMode(true);
876 }
877
878 virtual FormatToken getNextToken() {
879 if (GreaterStashed) {
880 FormatTok.NewlinesBefore = 0;
881 FormatTok.WhiteSpaceStart =
882 FormatTok.Tok.getLocation().getLocWithOffset(1);
883 FormatTok.WhiteSpaceLength = 0;
884 GreaterStashed = false;
885 return FormatTok;
886 }
887
888 FormatTok = FormatToken();
889 Lex.LexFromRawLexer(FormatTok.Tok);
890 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
891
892 // Consume and record whitespace until we find a significant token.
893 while (FormatTok.Tok.is(tok::unknown)) {
894 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
895 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
896
897 if (FormatTok.Tok.is(tok::eof))
898 return FormatTok;
899 Lex.LexFromRawLexer(FormatTok.Tok);
900 }
901
902 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000903 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
904 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000905 FormatTok.Tok.setKind(Info.getTokenID());
906 }
907
908 if (FormatTok.Tok.is(tok::greatergreater)) {
909 FormatTok.Tok.setKind(tok::greater);
910 GreaterStashed = true;
911 }
912
913 return FormatTok;
914 }
915
916private:
917 FormatToken FormatTok;
918 bool GreaterStashed;
919 Lexer &Lex;
920 SourceManager &SourceMgr;
921 IdentifierTable IdentTable;
922
923 /// Returns the text of \c FormatTok.
924 StringRef tokenText(Token &Tok) {
925 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
926 Tok.getLength());
927 }
928};
929
Daniel Jasperf7935112012-12-03 18:12:45 +0000930class Formatter : public UnwrappedLineConsumer {
931public:
932 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
933 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000934 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000935 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000936 }
937
Daniel Jasper61bd3a12012-12-04 21:05:31 +0000938 virtual ~Formatter() {
939 }
940
Daniel Jasperf7935112012-12-03 18:12:45 +0000941 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +0000942 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
943 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000944 StructuralError = Parser.parse();
945 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
946 E = UnwrappedLines.end();
947 I != E; ++I)
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000948 formatUnwrappedLine(*I);
Daniel Jasperf7935112012-12-03 18:12:45 +0000949 return Replaces;
950 }
951
952private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000953 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000954 UnwrappedLines.push_back(TheLine);
955 }
956
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000957 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 if (TheLine.Tokens.size() == 0)
959 return;
960
961 CharSourceRange LineRange =
962 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
963 TheLine.Tokens.back().Tok.getLocation());
964
965 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
966 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
967 Ranges[i].getBegin()) ||
968 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
969 LineRange.getBegin()))
970 continue;
971
972 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
973 Annotator.annotate();
974 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000975 Annotator.getAnnotations(), Replaces,
976 StructuralError);
Daniel Jasperf7935112012-12-03 18:12:45 +0000977 Formatter.format();
978 return;
979 }
980 }
981
982 FormatStyle Style;
983 Lexer &Lex;
984 SourceManager &SourceMgr;
985 tooling::Replacements Replaces;
986 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000987 std::vector<UnwrappedLine> UnwrappedLines;
988 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000989};
990
991tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
992 SourceManager &SourceMgr,
993 std::vector<CharSourceRange> Ranges) {
994 Formatter formatter(Style, Lex, SourceMgr, Ranges);
995 return formatter.format();
996}
997
998} // namespace format
999} // namespace clang