blob: 6983f73499b26a3993df5fc7cf3c6ab8174ecb5a [file] [log] [blame]
Daniel Jasperbac016b2012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
19#include "clang/Format/Format.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000021#include "clang/Basic/SourceManager.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
24
Daniel Jasper8822d3a2012-12-04 13:02:32 +000025#include <string>
26
Daniel Jasperbac016b2012-12-03 18:12:45 +000027namespace clang {
28namespace format {
29
30// FIXME: Move somewhere sane.
31struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000032 enum TokenType {
33 TT_Unknown,
34 TT_TemplateOpener,
35 TT_TemplateCloser,
36 TT_BinaryOperator,
37 TT_UnaryOperator,
Daniel Jasper98e6b4a2012-12-21 09:41:31 +000038 TT_TrailingUnaryOperator,
Daniel Jasper33182dd2012-12-05 14:57:28 +000039 TT_OverloadedOperator,
40 TT_PointerOrReference,
41 TT_ConditionalExpr,
Daniel Jasper1321eb52012-12-18 21:05:13 +000042 TT_CtorInitializerColon,
Daniel Jasper33182dd2012-12-05 14:57:28 +000043 TT_LineComment,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000044 TT_BlockComment,
45 TT_ObjCMethodSpecifier
Daniel Jasper33182dd2012-12-05 14:57:28 +000046 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000047
48 TokenType Type;
49
Daniel Jasperbac016b2012-12-03 18:12:45 +000050 bool SpaceRequiredBefore;
51 bool CanBreakBefore;
52 bool MustBreakBefore;
53};
54
55using llvm::MutableArrayRef;
56
57FormatStyle getLLVMStyle() {
58 FormatStyle LLVMStyle;
59 LLVMStyle.ColumnLimit = 80;
60 LLVMStyle.MaxEmptyLinesToKeep = 1;
61 LLVMStyle.PointerAndReferenceBindToType = false;
62 LLVMStyle.AccessModifierOffset = -2;
63 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000064 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000065 return LLVMStyle;
66}
67
68FormatStyle getGoogleStyle() {
69 FormatStyle GoogleStyle;
70 GoogleStyle.ColumnLimit = 80;
71 GoogleStyle.MaxEmptyLinesToKeep = 1;
72 GoogleStyle.PointerAndReferenceBindToType = true;
73 GoogleStyle.AccessModifierOffset = -1;
74 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000075 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000076 return GoogleStyle;
77}
78
79struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000080 unsigned PenaltyIndentLevel;
81};
82
83class UnwrappedLineFormatter {
84public:
85 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
86 const UnwrappedLine &Line,
87 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000088 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000089 : Style(Style), SourceMgr(SourceMgr), Line(Line),
90 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000091 StructuralError(StructuralError) {
Daniel Jasperbac016b2012-12-03 18:12:45 +000092 Parameters.PenaltyIndentLevel = 5;
93 }
94
95 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +000096 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +000097 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +000098
99 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000100 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000101 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000102 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000103 State.Indent.push_back(Indent + 4);
104 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000105 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000106 State.ForLoopVariablePos = 0;
107 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000108
109 // The first token has already been indented and thus consumed.
110 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000111
Daniel Jasper1321eb52012-12-18 21:05:13 +0000112 // Check whether the UnwrappedLine can be put onto a single line. If so,
113 // this is bound to be the optimal solution (by definition) and we don't
114 // need to analyze the entire solution space.
115 unsigned Columns = State.Column;
116 bool FitsOnALine = true;
117 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
118 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
119 Line.Tokens[i].Tok.getLength();
120 // A special case for the colon of a constructor initializer as this only
121 // needs to be put on a new line if the line needs to be split.
122 if (Columns > Style.ColumnLimit ||
123 (Annotations[i].MustBreakBefore &&
124 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
125 FitsOnALine = false;
126 break;
127 }
128 }
129
Daniel Jasperbac016b2012-12-03 18:12:45 +0000130 // Start iterating at 1 as we have correctly formatted of Token #0 above.
131 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000132 if (FitsOnALine) {
133 addTokenToState(false, false, State);
134 } else {
135 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
136 unsigned Break = calcPenalty(State, true, NoBreak);
137 addTokenToState(Break < NoBreak, false, State);
138 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000139 }
140 }
141
142private:
143 /// \brief The current state when indenting a unwrapped line.
144 ///
145 /// As the indenting tries different combinations this is copied by value.
146 struct IndentState {
147 /// \brief The number of used columns in the current line.
148 unsigned Column;
149
150 /// \brief The number of tokens already consumed.
151 unsigned ConsumedTokens;
152
153 /// \brief The position to which a specific parenthesis level needs to be
154 /// indented.
155 std::vector<unsigned> Indent;
156
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000157 /// \brief The position of the last space on each level.
158 ///
159 /// Used e.g. to break like:
160 /// functionCall(Parameter, otherCall(
161 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000162 std::vector<unsigned> LastSpace;
163
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000164 /// \brief The position the first "<<" operator encountered on each level.
165 ///
166 /// Used to align "<<" operators. 0 if no such operator has been encountered
167 /// on a level.
168 std::vector<unsigned> FirstLessLess;
169
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000170 /// \brief The column of the first variable in a for-loop declaration.
171 ///
172 /// Used to align the second variable if necessary.
173 unsigned ForLoopVariablePos;
174
175 /// \brief \c true if this line contains a continued for-loop section.
176 bool LineContainsContinuedForLoopSection;
177
Daniel Jasperbac016b2012-12-03 18:12:45 +0000178 /// \brief Comparison operator to be able to used \c IndentState in \c map.
179 bool operator<(const IndentState &Other) const {
180 if (Other.ConsumedTokens != ConsumedTokens)
181 return Other.ConsumedTokens > ConsumedTokens;
182 if (Other.Column != Column)
183 return Other.Column > Column;
184 if (Other.Indent.size() != Indent.size())
185 return Other.Indent.size() > Indent.size();
186 for (int i = 0, e = Indent.size(); i != e; ++i) {
187 if (Other.Indent[i] != Indent[i])
188 return Other.Indent[i] > Indent[i];
189 }
190 if (Other.LastSpace.size() != LastSpace.size())
191 return Other.LastSpace.size() > LastSpace.size();
192 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
193 if (Other.LastSpace[i] != LastSpace[i])
194 return Other.LastSpace[i] > LastSpace[i];
195 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000196 if (Other.FirstLessLess.size() != FirstLessLess.size())
197 return Other.FirstLessLess.size() > FirstLessLess.size();
198 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
199 if (Other.FirstLessLess[i] != FirstLessLess[i])
200 return Other.FirstLessLess[i] > FirstLessLess[i];
201 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000202 if (Other.ForLoopVariablePos != ForLoopVariablePos)
203 return Other.ForLoopVariablePos < ForLoopVariablePos;
204 if (Other.LineContainsContinuedForLoopSection !=
205 LineContainsContinuedForLoopSection)
206 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000207 return false;
208 }
209 };
210
Daniel Jasper20409152012-12-04 14:54:30 +0000211 /// \brief Appends the next token to \p State and updates information
212 /// necessary for indentation.
213 ///
214 /// Puts the token on the current line if \p Newline is \c true and adds a
215 /// line break and necessary indentation otherwise.
216 ///
217 /// If \p DryRun is \c false, also creates and stores the required
218 /// \c Replacement.
219 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000220 unsigned Index = State.ConsumedTokens;
221 const FormatToken &Current = Line.Tokens[Index];
222 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000223 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000224
225 if (Newline) {
226 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000227 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000229 } else if (Current.Tok.is(tok::lessless) &&
230 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000231 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000232 } else if (ParenLevel != 0 &&
233 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
234 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000235 // Indent and extra 4 spaces after '=' as it continues an expression.
236 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000237 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000238 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
239 Previous.Tok.is(tok::comma)) {
240 State.Column = State.ForLoopVariablePos;
241 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000242 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000243 }
244
245 if (Line.Tokens[0].Tok.is(tok::kw_for))
246 State.LineContainsContinuedForLoopSection =
247 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000248
Daniel Jasperbac016b2012-12-03 18:12:45 +0000249 if (!DryRun)
250 replaceWhitespace(Current, 1, State.Column);
251
Daniel Jaspera88bb452012-12-04 10:50:12 +0000252 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000253 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000254 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
255 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000256 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000257 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000258 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
259 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
260
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
262 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
263 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000264
Daniel Jasperbac016b2012-12-03 18:12:45 +0000265 if (!DryRun)
266 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000267
268 if (Previous.Tok.is(tok::l_paren) ||
269 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000271
Daniel Jasperbac016b2012-12-03 18:12:45 +0000272 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000273 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000274 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000275 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000276 }
Daniel Jasper20409152012-12-04 14:54:30 +0000277 moveStateToNextToken(State);
278 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000279
Daniel Jasper20409152012-12-04 14:54:30 +0000280 /// \brief Mark the next token as consumed in \p State and modify its stacks
281 /// accordingly.
282 void moveStateToNextToken(IndentState &State) {
283 unsigned Index = State.ConsumedTokens;
284 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000285 unsigned ParenLevel = State.Indent.size() - 1;
286
287 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
288 State.FirstLessLess[ParenLevel] = State.Column;
289
290 State.Column += Current.Tok.getLength();
Daniel Jasper20409152012-12-04 14:54:30 +0000291
292 // If we encounter an opening (, [ or <, we add a level to our stacks to
293 // prepare for the following tokens.
294 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
295 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
296 State.Indent.push_back(4 + State.LastSpace.back());
297 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000298 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000299 }
300
301 // If we encounter a closing ), ] or >, we can remove a level from our
302 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000303 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
304 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000305 State.Indent.pop_back();
306 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000307 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000308 }
309
310 ++State.ConsumedTokens;
311 }
312
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000313 /// \brief Calculate the panelty for splitting after the token at \p Index.
314 unsigned splitPenalty(unsigned Index) {
315 assert(Index < Line.Tokens.size() &&
316 "Tried to calculate penalty for splitting after the last token");
317 const FormatToken &Left = Line.Tokens[Index];
318 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000319
320 // In for-loops, prefer breaking at ',' and ';'.
321 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
322 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
323 return 20;
324
Daniel Jasper1321eb52012-12-18 21:05:13 +0000325 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000326 return 0;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000327 if (Left.Tok.is(tok::equal) || Left.Tok.is(tok::l_paren) ||
328 Left.Tok.is(tok::pipepipe) || Left.Tok.is(tok::ampamp))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 return 2;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000330
331 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
332 return 200;
333
Daniel Jasperbac016b2012-12-03 18:12:45 +0000334 return 3;
335 }
336
337 /// \brief Calculate the number of lines needed to format the remaining part
338 /// of the unwrapped line.
339 ///
340 /// Assumes the formatting so far has led to
341 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
342 /// added after the previous token.
343 ///
344 /// \param StopAt is used for optimization. If we can determine that we'll
345 /// definitely need at least \p StopAt additional lines, we already know of a
346 /// better solution.
347 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
348 // We are at the end of the unwrapped line, so we don't need any more lines.
349 if (State.ConsumedTokens >= Line.Tokens.size())
350 return 0;
351
352 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
353 return UINT_MAX;
354 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
355 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000356 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
357 State.LineContainsContinuedForLoopSection)
358 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000359
Daniel Jasper33182dd2012-12-05 14:57:28 +0000360 unsigned CurrentPenalty = 0;
361 if (NewLine) {
362 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper1321eb52012-12-18 21:05:13 +0000363 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000364 }
365
Daniel Jasper20409152012-12-04 14:54:30 +0000366 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000367
368 // Exceeding column limit is bad.
369 if (State.Column > Style.ColumnLimit)
370 return UINT_MAX;
371
Daniel Jasperbac016b2012-12-03 18:12:45 +0000372 if (StopAt <= CurrentPenalty)
373 return UINT_MAX;
374 StopAt -= CurrentPenalty;
375
Daniel Jasperbac016b2012-12-03 18:12:45 +0000376 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000377 if (I != Memory.end()) {
378 // If this state has already been examined, we can safely return the
379 // previous result if we
380 // - have not hit the optimatization (and thus returned UINT_MAX) OR
381 // - are now computing for a smaller or equal StopAt.
382 unsigned SavedResult = I->second.first;
383 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000384 if (SavedResult != UINT_MAX)
385 return SavedResult + CurrentPenalty;
386 else if (StopAt <= SavedStopAt)
387 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000388 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000389
390 unsigned NoBreak = calcPenalty(State, false, StopAt);
391 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
392 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000393
394 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
395 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000396 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000397
398 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399 }
400
401 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
402 /// each \c FormatToken.
403 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
404 unsigned Spaces) {
405 Replaces.insert(tooling::Replacement(
406 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
407 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
408 }
409
410 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000411 /// of the \c UnwrappedLine if there was no structural parsing error.
412 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000413 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000414 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000415 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
416 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
417
418 unsigned Newlines =
419 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
420 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
421 if (Newlines == 0 && Offset != 0)
422 Newlines = 1;
423 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000424 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
425 Token.Tok.is(tok::kw_private)) &&
426 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000427 Indent += Style.AccessModifierOffset;
428 replaceWhitespace(Token, Newlines, Indent);
429 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000430 }
431
432 FormatStyle Style;
433 SourceManager &SourceMgr;
434 const UnwrappedLine &Line;
435 const std::vector<TokenAnnotation> &Annotations;
436 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000437 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000438
Daniel Jasper33182dd2012-12-05 14:57:28 +0000439 // A map from an indent state to a pair (Result, Used-StopAt).
440 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
441 StateMap Memory;
442
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 OptimizationParameters Parameters;
444};
445
446/// \brief Determines extra information about the tokens comprising an
447/// \c UnwrappedLine.
448class TokenAnnotator {
449public:
450 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
451 SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000452 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000453 }
454
455 /// \brief A parser that gathers additional information about tokens.
456 ///
457 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
458 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
459 /// into template parameter lists.
460 class AnnotatingParser {
461 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000462 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000463 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000464 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000465 }
466
Daniel Jasper20409152012-12-04 14:54:30 +0000467 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000468 while (Index < Tokens.size()) {
469 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000470 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000471 next();
472 return true;
473 }
474 if (Tokens[Index].Tok.is(tok::r_paren) ||
475 Tokens[Index].Tok.is(tok::r_square))
476 return false;
477 if (Tokens[Index].Tok.is(tok::pipepipe) ||
478 Tokens[Index].Tok.is(tok::ampamp) ||
479 Tokens[Index].Tok.is(tok::question) ||
480 Tokens[Index].Tok.is(tok::colon))
481 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000482 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000483 }
484 return false;
485 }
486
Daniel Jasper20409152012-12-04 14:54:30 +0000487 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488 while (Index < Tokens.size()) {
489 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000490 next();
491 return true;
492 }
493 if (Tokens[Index].Tok.is(tok::r_square))
494 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000495 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000496 }
497 return false;
498 }
499
Daniel Jasper20409152012-12-04 14:54:30 +0000500 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501 while (Index < Tokens.size()) {
502 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000503 next();
504 return true;
505 }
506 if (Tokens[Index].Tok.is(tok::r_paren))
507 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000508 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000509 }
510 return false;
511 }
512
Daniel Jasper20409152012-12-04 14:54:30 +0000513 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000514 while (Index < Tokens.size()) {
515 if (Tokens[Index].Tok.is(tok::colon)) {
516 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
517 next();
518 return true;
519 }
Daniel Jasper20409152012-12-04 14:54:30 +0000520 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000521 }
522 return false;
523 }
524
Daniel Jasper20409152012-12-04 14:54:30 +0000525 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000526 unsigned CurrentIndex = Index;
527 next();
528 switch (Tokens[CurrentIndex].Tok.getKind()) {
529 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000530 parseParens();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000531 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
532 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
533 next();
534 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 break;
536 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000537 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000538 break;
539 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000540 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000541 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
542 else {
543 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
544 Index = CurrentIndex + 1;
545 }
546 break;
547 case tok::greater:
548 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
549 break;
550 case tok::kw_operator:
551 if (!Tokens[Index].Tok.is(tok::l_paren))
552 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
553 next();
554 break;
555 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000556 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000557 break;
558 default:
559 break;
560 }
561 }
562
563 void parseLine() {
564 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000565 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 }
567 }
568
569 void next() {
570 ++Index;
571 }
572
573 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 const SmallVector<FormatToken, 16> &Tokens;
575 std::vector<TokenAnnotation> &Annotations;
576 unsigned Index;
577 };
578
579 void annotate() {
580 Annotations.clear();
581 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
582 Annotations.push_back(TokenAnnotation());
583 }
584
Manuel Klimek0be4b362012-12-03 20:55:42 +0000585 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000586 Parser.parseLine();
587
588 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000589 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000590 (Line.Tokens.size() > 0 &&
591 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
593 TokenAnnotation &Annotation = Annotations[i];
594
595 Annotation.CanBreakBefore =
596 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
597
Daniel Jasper1321eb52012-12-18 21:05:13 +0000598 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
599 Annotation.MustBreakBefore = true;
600 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000601 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
602 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
603 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000604 Annotation.CanBreakBefore = true;
605 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000606 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
607 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
608 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000609 // Don't break this identifier as ':' or identifier
610 // before it will break.
611 Annotation.CanBreakBefore = false;
612 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000613 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000614 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000615 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000616 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000617 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000618 Annotation.SpaceRequiredBefore =
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000619 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
620 (i != e - 1);
621 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000622 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
623 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000624 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000625 } else if (
626 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000627 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000628 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000629 Annotation.SpaceRequiredBefore = false;
630 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
631 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000632 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
633 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
635 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000636 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000637 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000638 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000639 else
640 Annotation.SpaceRequiredBefore = false;
641 } else if (
642 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
643 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
644 Annotation.SpaceRequiredBefore = true;
645 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000646 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000647 Line.Tokens[i].Tok.is(tok::l_paren)) {
648 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000649 } else if (Line.Tokens[i].Tok.is(tok::less) &&
650 Line.Tokens[0].Tok.is(tok::hash)) {
651 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000652 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
653 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000654 // Don't space between ')' and <id>
655 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000656 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
657 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000658 // Don't space between ':' and '('
659 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000660 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
661 Annotation.SpaceRequiredBefore = false;
662 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000663 Annotation.SpaceRequiredBefore =
664 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
665 }
666
667 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
668 (Line.Tokens[i].Tok.is(tok::string_literal) &&
669 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
670 Annotation.MustBreakBefore = true;
671 }
672
673 if (Annotation.MustBreakBefore)
674 Annotation.CanBreakBefore = true;
675 }
676 }
677
678 const std::vector<TokenAnnotation> &getAnnotations() {
679 return Annotations;
680 }
681
682private:
683 void determineTokenTypes() {
Daniel Jasper33182dd2012-12-05 14:57:28 +0000684 bool AssignmentEncountered = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000685 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
686 TokenAnnotation &Annotation = Annotations[i];
687 const FormatToken &Tok = Line.Tokens[i];
688
Daniel Jasper675d2e32012-12-21 10:20:02 +0000689 if (getBinOpPrecedence(Tok.Tok.getKind(), true, true) == prec::Assignment)
Daniel Jasper33182dd2012-12-05 14:57:28 +0000690 AssignmentEncountered = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000691
Daniel Jasper675d2e32012-12-21 10:20:02 +0000692 if (Annotation.Type != TokenAnnotation::TT_Unknown)
693 continue;
694
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000695 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Daniel Jasper33182dd2012-12-05 14:57:28 +0000696 Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000697 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
698 Annotation.Type = determinePlusMinusUsage(i);
699 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
700 Annotation.Type = determineIncrementUsage(i);
701 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000702 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000703 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000704 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000705 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000706 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
707 Tok.Tok.getLength());
708 if (Data.startswith("//"))
709 Annotation.Type = TokenAnnotation::TT_LineComment;
710 else
711 Annotation.Type = TokenAnnotation::TT_BlockComment;
712 }
713 }
714 }
715
Daniel Jasperbac016b2012-12-03 18:12:45 +0000716 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper675d2e32012-12-21 10:20:02 +0000717 // Comma is a binary operator, but does not behave a such wrt. formatting.
718 return getBinOpPrecedence(Tok.Tok.getKind(), true, true) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000719 }
720
Daniel Jasper112fb272012-12-05 07:51:39 +0000721 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Daniel Jasper33182dd2012-12-05 14:57:28 +0000722 bool AssignmentEncountered) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000723 if (Index == Annotations.size())
724 return TokenAnnotation::TT_Unknown;
725
726 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
727 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
728 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
729 return TokenAnnotation::TT_UnaryOperator;
730
731 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000732 Line.Tokens[Index + 1].Tok.isLiteral() ||
733 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 return TokenAnnotation::TT_BinaryOperator;
735
Daniel Jasper112fb272012-12-05 07:51:39 +0000736 // It is very unlikely that we are going to find a pointer or reference type
737 // definition on the RHS of an assignment.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000738 if (AssignmentEncountered)
Daniel Jasper112fb272012-12-05 07:51:39 +0000739 return TokenAnnotation::TT_BinaryOperator;
740
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 return TokenAnnotation::TT_PointerOrReference;
742 }
743
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000744 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
745 // At the start of the line, +/- specific ObjectiveC method declarations.
746 if (Index == 0)
747 return TokenAnnotation::TT_ObjCMethodSpecifier;
748
749 // Use heuristics to recognize unary operators.
750 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
751 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
752 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
753 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
754 return TokenAnnotation::TT_UnaryOperator;
755
756 // There can't be to consecutive binary operators.
757 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
758 return TokenAnnotation::TT_UnaryOperator;
759
760 // Fall back to marking the token as binary operator.
761 return TokenAnnotation::TT_BinaryOperator;
762 }
763
764 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
765 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
766 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
767 return TokenAnnotation::TT_TrailingUnaryOperator;
768
769 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000770 }
771
772 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000773 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
774 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000775 if (Left.is(tok::kw_template) && Right.is(tok::less))
776 return true;
777 if (Left.is(tok::arrow) || Right.is(tok::arrow))
778 return false;
779 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
780 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000781 if (Left.is(tok::at) && Right.is(tok::identifier))
782 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
784 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000785 if (Right.is(tok::amp) || Right.is(tok::star))
786 return Left.isLiteral() ||
787 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
788 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000789 if (Left.is(tok::amp) || Left.is(tok::star))
790 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
791 if (Right.is(tok::star) && Left.is(tok::l_paren))
792 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000793 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
794 Right.is(tok::r_square))
795 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000796 if (Left.is(tok::coloncolon) ||
797 (Right.is(tok::coloncolon) &&
798 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000799 return false;
800 if (Left.is(tok::period) || Right.is(tok::period))
801 return false;
802 if (Left.is(tok::colon) || Right.is(tok::colon))
803 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000804 if (Left.is(tok::l_paren))
805 return false;
806 if (Left.is(tok::hash))
807 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000808 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000809 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
810 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
811 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
812 Left.isNot(tok::kw_typeof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000813 }
814 return true;
815 }
816
817 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000818 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
819 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000821 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
822 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
823 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
824 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
825 Left.Tok.is(tok::l_brace) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000826 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
827 }
828
829 const UnwrappedLine &Line;
830 FormatStyle Style;
831 SourceManager &SourceMgr;
832 std::vector<TokenAnnotation> Annotations;
833};
834
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000835class LexerBasedFormatTokenSource : public FormatTokenSource {
836public:
837 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000838 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000839 IdentTable(Lex.getLangOpts()) {
840 Lex.SetKeepWhitespaceMode(true);
841 }
842
843 virtual FormatToken getNextToken() {
844 if (GreaterStashed) {
845 FormatTok.NewlinesBefore = 0;
846 FormatTok.WhiteSpaceStart =
847 FormatTok.Tok.getLocation().getLocWithOffset(1);
848 FormatTok.WhiteSpaceLength = 0;
849 GreaterStashed = false;
850 return FormatTok;
851 }
852
853 FormatTok = FormatToken();
854 Lex.LexFromRawLexer(FormatTok.Tok);
855 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
856
857 // Consume and record whitespace until we find a significant token.
858 while (FormatTok.Tok.is(tok::unknown)) {
859 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
860 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
861
862 if (FormatTok.Tok.is(tok::eof))
863 return FormatTok;
864 Lex.LexFromRawLexer(FormatTok.Tok);
865 }
866
867 if (FormatTok.Tok.is(tok::raw_identifier)) {
868 const IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
869 FormatTok.Tok.setKind(Info.getTokenID());
870 }
871
872 if (FormatTok.Tok.is(tok::greatergreater)) {
873 FormatTok.Tok.setKind(tok::greater);
874 GreaterStashed = true;
875 }
876
877 return FormatTok;
878 }
879
880private:
881 FormatToken FormatTok;
882 bool GreaterStashed;
883 Lexer &Lex;
884 SourceManager &SourceMgr;
885 IdentifierTable IdentTable;
886
887 /// Returns the text of \c FormatTok.
888 StringRef tokenText(Token &Tok) {
889 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
890 Tok.getLength());
891 }
892};
893
Daniel Jasperbac016b2012-12-03 18:12:45 +0000894class Formatter : public UnwrappedLineConsumer {
895public:
896 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
897 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000898 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000899 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000900 }
901
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000902 virtual ~Formatter() {
903 }
904
Daniel Jasperbac016b2012-12-03 18:12:45 +0000905 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000906 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
907 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000908 StructuralError = Parser.parse();
909 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
910 E = UnwrappedLines.end();
911 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000912 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000913 return Replaces;
914 }
915
916private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000917 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000918 UnwrappedLines.push_back(TheLine);
919 }
920
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000921 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000922 if (TheLine.Tokens.size() == 0)
923 return;
924
925 CharSourceRange LineRange =
926 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
927 TheLine.Tokens.back().Tok.getLocation());
928
929 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
930 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
931 Ranges[i].getBegin()) ||
932 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
933 LineRange.getBegin()))
934 continue;
935
936 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
937 Annotator.annotate();
938 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000939 Annotator.getAnnotations(), Replaces,
940 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000941 Formatter.format();
942 return;
943 }
944 }
945
946 FormatStyle Style;
947 Lexer &Lex;
948 SourceManager &SourceMgr;
949 tooling::Replacements Replaces;
950 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000951 std::vector<UnwrappedLine> UnwrappedLines;
952 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000953};
954
955tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
956 SourceManager &SourceMgr,
957 std::vector<CharSourceRange> Ranges) {
958 Formatter formatter(Style, Lex, SourceMgr, Ranges);
959 return formatter.format();
960}
961
962} // namespace format
963} // namespace clang