blob: ad85a8ecf2237e3a7a98e737f90b7f7f7d2c09e3 [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,
Daniel Jaspercd1a32b2012-12-21 17:58:39 +000045 TT_DirectorySeparator,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000046 TT_ObjCMethodSpecifier
Daniel Jasper33182dd2012-12-05 14:57:28 +000047 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000048
49 TokenType Type;
50
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000065 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-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 Kornienko15757312012-12-06 18:03:27 +000076 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000077 return GoogleStyle;
78}
79
80struct OptimizationParameters {
Daniel Jasperbac016b2012-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 Kornienkocff563c2012-12-04 17:27:50 +000089 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000090 : Style(Style), SourceMgr(SourceMgr), Line(Line),
91 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000092 StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +000093 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperbac016b2012-12-03 18:12:45 +000094 }
95
96 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +000097 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +000098 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +000099
100 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000101 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000102 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000103 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000104 State.Indent.push_back(Indent + 4);
105 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000106 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000107 State.ForLoopVariablePos = 0;
108 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000109
110 // The first token has already been indented and thus consumed.
111 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000112
Daniel Jasper1321eb52012-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 Jasperbac016b2012-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 Jasper1321eb52012-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 Jasperbac016b2012-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 Jasper3b5943f2012-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 Jasperbac016b2012-12-03 18:12:45 +0000163 std::vector<unsigned> LastSpace;
164
Daniel Jasper3b5943f2012-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 Jaspera324a0e2012-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 Jasperbac016b2012-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 Jasper3b5943f2012-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 Jaspera324a0e2012-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 Jasperbac016b2012-12-03 18:12:45 +0000208 return false;
209 }
210 };
211
Daniel Jasper20409152012-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 Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000224 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000225
226 if (Newline) {
227 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000228 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000229 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000230 } else if (Current.Tok.is(tok::lessless) &&
231 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000232 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-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 Jasper20409152012-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 Jasperbac016b2012-12-03 18:12:45 +0000238 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera324a0e2012-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 Jasperbac016b2012-12-03 18:12:45 +0000243 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-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 Jasper20409152012-12-04 14:54:30 +0000249
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250 if (!DryRun)
251 replaceWhitespace(Current, 1, State.Column);
252
Daniel Jaspera88bb452012-12-04 10:50:12 +0000253 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000254 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000255 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
256 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000257 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000258 } else {
Daniel Jaspera324a0e2012-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 Jasperbac016b2012-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 Jasper20409152012-12-04 14:54:30 +0000265
Daniel Jasperbac016b2012-12-03 18:12:45 +0000266 if (!DryRun)
267 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000268
269 if (Previous.Tok.is(tok::l_paren) ||
270 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000271 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000272
Daniel Jasperbac016b2012-12-03 18:12:45 +0000273 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000274 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000275 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000276 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000277 }
Daniel Jasper20409152012-12-04 14:54:30 +0000278 moveStateToNextToken(State);
279 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000280
Daniel Jasper20409152012-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 Jasper3b5943f2012-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 Jasper20409152012-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 Jasper3b5943f2012-12-06 09:56:08 +0000299 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000300 }
301
302 // If we encounter a closing ), ] or >, we can remove a level from our
303 // stacks.
Daniel Jaspera88bb452012-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 Jasperbac016b2012-12-03 18:12:45 +0000306 State.Indent.pop_back();
307 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000308 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000309 }
310
311 ++State.ConsumedTokens;
312 }
313
Daniel Jasper9a0b4942012-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 Jaspera324a0e2012-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 Jasper1321eb52012-12-18 21:05:13 +0000326 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000327 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000328 if (Left.Tok.is(tok::l_paren))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329 return 2;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000330
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000331 prec::Level Level =
332 getBinOpPrecedence(Line.Tokens[Index].Tok.getKind(), true, true);
333 if (Level != prec::Unknown)
334 return Level;
335
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000336 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
337 return 200;
338
Daniel Jasperbac016b2012-12-03 18:12:45 +0000339 return 3;
340 }
341
342 /// \brief Calculate the number of lines needed to format the remaining part
343 /// of the unwrapped line.
344 ///
345 /// Assumes the formatting so far has led to
346 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
347 /// added after the previous token.
348 ///
349 /// \param StopAt is used for optimization. If we can determine that we'll
350 /// definitely need at least \p StopAt additional lines, we already know of a
351 /// better solution.
352 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
353 // We are at the end of the unwrapped line, so we don't need any more lines.
354 if (State.ConsumedTokens >= Line.Tokens.size())
355 return 0;
356
357 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
358 return UINT_MAX;
359 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
360 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000361 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
362 State.LineContainsContinuedForLoopSection)
363 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000364
Daniel Jasper33182dd2012-12-05 14:57:28 +0000365 unsigned CurrentPenalty = 0;
366 if (NewLine) {
367 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper1321eb52012-12-18 21:05:13 +0000368 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000369 }
370
Daniel Jasper20409152012-12-04 14:54:30 +0000371 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000372
373 // Exceeding column limit is bad.
374 if (State.Column > Style.ColumnLimit)
375 return UINT_MAX;
376
Daniel Jasperbac016b2012-12-03 18:12:45 +0000377 if (StopAt <= CurrentPenalty)
378 return UINT_MAX;
379 StopAt -= CurrentPenalty;
380
Daniel Jasperbac016b2012-12-03 18:12:45 +0000381 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000382 if (I != Memory.end()) {
383 // If this state has already been examined, we can safely return the
384 // previous result if we
385 // - have not hit the optimatization (and thus returned UINT_MAX) OR
386 // - are now computing for a smaller or equal StopAt.
387 unsigned SavedResult = I->second.first;
388 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000389 if (SavedResult != UINT_MAX)
390 return SavedResult + CurrentPenalty;
391 else if (StopAt <= SavedStopAt)
392 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000393 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000394
395 unsigned NoBreak = calcPenalty(State, false, StopAt);
396 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
397 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000398
399 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
400 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000401 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000402
403 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000404 }
405
406 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
407 /// each \c FormatToken.
408 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
409 unsigned Spaces) {
410 Replaces.insert(tooling::Replacement(
411 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
412 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
413 }
414
415 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000416 /// of the \c UnwrappedLine if there was no structural parsing error.
417 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000418 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000419 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000420 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
421 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
422
423 unsigned Newlines =
424 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
425 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
426 if (Newlines == 0 && Offset != 0)
427 Newlines = 1;
428 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000429 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
430 Token.Tok.is(tok::kw_private)) &&
431 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000432 Indent += Style.AccessModifierOffset;
433 replaceWhitespace(Token, Newlines, Indent);
434 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000435 }
436
437 FormatStyle Style;
438 SourceManager &SourceMgr;
439 const UnwrappedLine &Line;
440 const std::vector<TokenAnnotation> &Annotations;
441 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000442 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443
Daniel Jasper33182dd2012-12-05 14:57:28 +0000444 // A map from an indent state to a pair (Result, Used-StopAt).
445 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
446 StateMap Memory;
447
Daniel Jasperbac016b2012-12-03 18:12:45 +0000448 OptimizationParameters Parameters;
449};
450
451/// \brief Determines extra information about the tokens comprising an
452/// \c UnwrappedLine.
453class TokenAnnotator {
454public:
455 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
456 SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000457 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000458 }
459
460 /// \brief A parser that gathers additional information about tokens.
461 ///
462 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
463 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
464 /// into template parameter lists.
465 class AnnotatingParser {
466 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000467 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000468 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000469 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000470 }
471
Daniel Jasper20409152012-12-04 14:54:30 +0000472 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000473 while (Index < Tokens.size()) {
474 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000475 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000476 next();
477 return true;
478 }
479 if (Tokens[Index].Tok.is(tok::r_paren) ||
480 Tokens[Index].Tok.is(tok::r_square))
481 return false;
482 if (Tokens[Index].Tok.is(tok::pipepipe) ||
483 Tokens[Index].Tok.is(tok::ampamp) ||
484 Tokens[Index].Tok.is(tok::question) ||
485 Tokens[Index].Tok.is(tok::colon))
486 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000487 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488 }
489 return false;
490 }
491
Daniel Jasper20409152012-12-04 14:54:30 +0000492 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000493 while (Index < Tokens.size()) {
494 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000495 next();
496 return true;
497 }
498 if (Tokens[Index].Tok.is(tok::r_square))
499 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000500 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501 }
502 return false;
503 }
504
Daniel Jasper20409152012-12-04 14:54:30 +0000505 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000506 while (Index < Tokens.size()) {
507 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000508 next();
509 return true;
510 }
511 if (Tokens[Index].Tok.is(tok::r_paren))
512 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000513 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000514 }
515 return false;
516 }
517
Daniel Jasper20409152012-12-04 14:54:30 +0000518 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000519 while (Index < Tokens.size()) {
520 if (Tokens[Index].Tok.is(tok::colon)) {
521 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
522 next();
523 return true;
524 }
Daniel Jasper20409152012-12-04 14:54:30 +0000525 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000526 }
527 return false;
528 }
529
Daniel Jasper20409152012-12-04 14:54:30 +0000530 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000531 unsigned CurrentIndex = Index;
532 next();
533 switch (Tokens[CurrentIndex].Tok.getKind()) {
534 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000535 parseParens();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000536 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
537 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
538 next();
539 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000540 break;
541 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000542 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000543 break;
544 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000545 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000546 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
547 else {
548 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
549 Index = CurrentIndex + 1;
550 }
551 break;
552 case tok::greater:
553 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
554 break;
555 case tok::kw_operator:
556 if (!Tokens[Index].Tok.is(tok::l_paren))
557 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
558 next();
559 break;
560 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000561 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000562 break;
563 default:
564 break;
565 }
566 }
567
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000568 void parseIncludeDirective() {
569 while (Index < Tokens.size()) {
570 if (Tokens[Index].Tok.is(tok::slash))
571 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
572 else if (Tokens[Index].Tok.is(tok::less))
573 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
574 else if (Tokens[Index].Tok.is(tok::greater))
575 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
576 next();
577 }
578 }
579
580 void parsePreprocessorDirective() {
581 next();
582 if (Index >= Tokens.size())
583 return;
584 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
585 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000586 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000587 parseIncludeDirective();
588 break;
589 default:
590 break;
591 }
592 }
593
Daniel Jasperbac016b2012-12-03 18:12:45 +0000594 void parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000595 if (Tokens[Index].Tok.is(tok::hash)) {
596 parsePreprocessorDirective();
597 return;
598 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000599 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000600 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000601 }
602 }
603
604 void next() {
605 ++Index;
606 }
607
608 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000609 const SmallVector<FormatToken, 16> &Tokens;
610 std::vector<TokenAnnotation> &Annotations;
611 unsigned Index;
612 };
613
614 void annotate() {
615 Annotations.clear();
616 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
617 Annotations.push_back(TokenAnnotation());
618 }
619
Manuel Klimek0be4b362012-12-03 20:55:42 +0000620 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000621 Parser.parseLine();
622
623 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000624 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000625 (Line.Tokens.size() > 0 &&
626 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000627 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
628 TokenAnnotation &Annotation = Annotations[i];
629
630 Annotation.CanBreakBefore =
631 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
632
Daniel Jasper1321eb52012-12-18 21:05:13 +0000633 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
634 Annotation.MustBreakBefore = true;
635 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000636 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
637 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
638 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000639 Annotation.CanBreakBefore = true;
640 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000641 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
642 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
643 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000644 // Don't break this identifier as ':' or identifier
645 // before it will break.
646 Annotation.CanBreakBefore = false;
647 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000648 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000649 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000650 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000651 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000652 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000653 Annotation.SpaceRequiredBefore =
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000654 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
655 (i != e - 1);
656 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000657 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
658 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000659 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000660 } else if (
661 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000662 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000663 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000664 Annotation.SpaceRequiredBefore = false;
665 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
666 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000667 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
668 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000669 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
670 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000671 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000672 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000673 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000674 else
675 Annotation.SpaceRequiredBefore = false;
676 } else if (
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000677 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
678 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
679 Annotation.SpaceRequiredBefore = false;
680 } else if (
Daniel Jasperbac016b2012-12-03 18:12:45 +0000681 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
682 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
683 Annotation.SpaceRequiredBefore = true;
684 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000685 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000686 Line.Tokens[i].Tok.is(tok::l_paren)) {
687 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000688 } else if (Line.Tokens[i].Tok.is(tok::less) &&
689 Line.Tokens[0].Tok.is(tok::hash)) {
690 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000691 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
692 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000693 // Don't space between ')' and <id>
694 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000695 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
696 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000697 // Don't space between ':' and '('
698 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000699 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
700 Annotation.SpaceRequiredBefore = false;
701 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000702 Annotation.SpaceRequiredBefore =
703 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
704 }
705
706 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
707 (Line.Tokens[i].Tok.is(tok::string_literal) &&
708 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
709 Annotation.MustBreakBefore = true;
710 }
711
712 if (Annotation.MustBreakBefore)
713 Annotation.CanBreakBefore = true;
714 }
715 }
716
717 const std::vector<TokenAnnotation> &getAnnotations() {
718 return Annotations;
719 }
720
721private:
722 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000723 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000724 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
725 TokenAnnotation &Annotation = Annotations[i];
726 const FormatToken &Tok = Line.Tokens[i];
727
Daniel Jasper675d2e32012-12-21 10:20:02 +0000728 if (getBinOpPrecedence(Tok.Tok.getKind(), true, true) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000729 IsRHS = true;
730 else if (Tok.Tok.is(tok::kw_return))
731 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000732
Daniel Jasper675d2e32012-12-21 10:20:02 +0000733 if (Annotation.Type != TokenAnnotation::TT_Unknown)
734 continue;
735
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000736 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000737 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000738 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
739 Annotation.Type = determinePlusMinusUsage(i);
740 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
741 Annotation.Type = determineIncrementUsage(i);
742 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000743 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000744 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000745 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000746 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000747 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
748 Tok.Tok.getLength());
749 if (Data.startswith("//"))
750 Annotation.Type = TokenAnnotation::TT_LineComment;
751 else
752 Annotation.Type = TokenAnnotation::TT_BlockComment;
753 }
754 }
755 }
756
Daniel Jasperbac016b2012-12-03 18:12:45 +0000757 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000758 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper675d2e32012-12-21 10:20:02 +0000759 return getBinOpPrecedence(Tok.Tok.getKind(), true, true) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000760 }
761
Daniel Jasper112fb272012-12-05 07:51:39 +0000762 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Nico Weber00d5a042012-12-23 01:07:46 +0000763 bool IsRHS) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000764 if (Index == Annotations.size())
765 return TokenAnnotation::TT_Unknown;
766
767 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
768 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
Nico Weber00d5a042012-12-23 01:07:46 +0000769 Line.Tokens[Index - 1].Tok.is(tok::kw_return) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000770 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
771 return TokenAnnotation::TT_UnaryOperator;
772
773 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000774 Line.Tokens[Index + 1].Tok.isLiteral() ||
775 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000776 return TokenAnnotation::TT_BinaryOperator;
777
Daniel Jasper112fb272012-12-05 07:51:39 +0000778 // It is very unlikely that we are going to find a pointer or reference type
779 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000780 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000781 return TokenAnnotation::TT_BinaryOperator;
782
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 return TokenAnnotation::TT_PointerOrReference;
784 }
785
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000786 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
787 // At the start of the line, +/- specific ObjectiveC method declarations.
788 if (Index == 0)
789 return TokenAnnotation::TT_ObjCMethodSpecifier;
790
791 // Use heuristics to recognize unary operators.
792 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
793 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
794 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
795 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
796 return TokenAnnotation::TT_UnaryOperator;
797
798 // There can't be to consecutive binary operators.
799 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
800 return TokenAnnotation::TT_UnaryOperator;
801
802 // Fall back to marking the token as binary operator.
803 return TokenAnnotation::TT_BinaryOperator;
804 }
805
806 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
807 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
808 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
809 return TokenAnnotation::TT_TrailingUnaryOperator;
810
811 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000812 }
813
814 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000815 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
816 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000817 if (Left.is(tok::kw_template) && Right.is(tok::less))
818 return true;
819 if (Left.is(tok::arrow) || Right.is(tok::arrow))
820 return false;
821 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
822 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000823 if (Left.is(tok::at) && Right.is(tok::identifier))
824 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000825 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
826 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000827 if (Right.is(tok::amp) || Right.is(tok::star))
828 return Left.isLiteral() ||
829 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
830 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000831 if (Left.is(tok::amp) || Left.is(tok::star))
832 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
833 if (Right.is(tok::star) && Left.is(tok::l_paren))
834 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000835 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
836 Right.is(tok::r_square))
837 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000838 if (Left.is(tok::coloncolon) ||
839 (Right.is(tok::coloncolon) &&
840 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000841 return false;
842 if (Left.is(tok::period) || Right.is(tok::period))
843 return false;
844 if (Left.is(tok::colon) || Right.is(tok::colon))
845 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000846 if (Left.is(tok::l_paren))
847 return false;
848 if (Left.is(tok::hash))
849 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000850 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000851 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
852 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
853 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
854 Left.isNot(tok::kw_typeof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000855 }
856 return true;
857 }
858
859 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000860 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
861 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000862 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000863 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
864 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
865 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
866 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
867 Left.Tok.is(tok::l_brace) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000868 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
869 }
870
871 const UnwrappedLine &Line;
872 FormatStyle Style;
873 SourceManager &SourceMgr;
874 std::vector<TokenAnnotation> Annotations;
875};
876
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000877class LexerBasedFormatTokenSource : public FormatTokenSource {
878public:
879 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000880 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000881 IdentTable(Lex.getLangOpts()) {
882 Lex.SetKeepWhitespaceMode(true);
883 }
884
885 virtual FormatToken getNextToken() {
886 if (GreaterStashed) {
887 FormatTok.NewlinesBefore = 0;
888 FormatTok.WhiteSpaceStart =
889 FormatTok.Tok.getLocation().getLocWithOffset(1);
890 FormatTok.WhiteSpaceLength = 0;
891 GreaterStashed = false;
892 return FormatTok;
893 }
894
895 FormatTok = FormatToken();
896 Lex.LexFromRawLexer(FormatTok.Tok);
897 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
898
899 // Consume and record whitespace until we find a significant token.
900 while (FormatTok.Tok.is(tok::unknown)) {
901 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
902 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
903
904 if (FormatTok.Tok.is(tok::eof))
905 return FormatTok;
906 Lex.LexFromRawLexer(FormatTok.Tok);
907 }
908
909 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000910 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
911 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000912 FormatTok.Tok.setKind(Info.getTokenID());
913 }
914
915 if (FormatTok.Tok.is(tok::greatergreater)) {
916 FormatTok.Tok.setKind(tok::greater);
917 GreaterStashed = true;
918 }
919
920 return FormatTok;
921 }
922
923private:
924 FormatToken FormatTok;
925 bool GreaterStashed;
926 Lexer &Lex;
927 SourceManager &SourceMgr;
928 IdentifierTable IdentTable;
929
930 /// Returns the text of \c FormatTok.
931 StringRef tokenText(Token &Tok) {
932 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
933 Tok.getLength());
934 }
935};
936
Daniel Jasperbac016b2012-12-03 18:12:45 +0000937class Formatter : public UnwrappedLineConsumer {
938public:
939 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
940 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000941 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000942 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000943 }
944
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000945 virtual ~Formatter() {
946 }
947
Daniel Jasperbac016b2012-12-03 18:12:45 +0000948 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000949 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
950 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000951 StructuralError = Parser.parse();
952 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
953 E = UnwrappedLines.end();
954 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000955 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 return Replaces;
957 }
958
959private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000960 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000961 UnwrappedLines.push_back(TheLine);
962 }
963
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000964 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000965 if (TheLine.Tokens.size() == 0)
966 return;
967
968 CharSourceRange LineRange =
969 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
970 TheLine.Tokens.back().Tok.getLocation());
971
972 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
973 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
974 Ranges[i].getBegin()) ||
975 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
976 LineRange.getBegin()))
977 continue;
978
979 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
980 Annotator.annotate();
981 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000982 Annotator.getAnnotations(), Replaces,
983 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000984 Formatter.format();
985 return;
986 }
987 }
988
989 FormatStyle Style;
990 Lexer &Lex;
991 SourceManager &SourceMgr;
992 tooling::Replacements Replaces;
993 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000994 std::vector<UnwrappedLine> UnwrappedLines;
995 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000996};
997
998tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
999 SourceManager &SourceMgr,
1000 std::vector<CharSourceRange> Ranges) {
1001 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1002 return formatter.format();
1003}
1004
1005} // namespace format
1006} // namespace clang