blob: 056376a4e28d0e4e6362d4e97154b16d569fccbb [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
Daniel Jaspercf225b62012-12-24 13:43:52 +000056static prec::Level getPrecedence(const FormatToken &Tok) {
57 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
58}
59
Daniel Jasperbac016b2012-12-03 18:12:45 +000060using llvm::MutableArrayRef;
61
62FormatStyle getLLVMStyle() {
63 FormatStyle LLVMStyle;
64 LLVMStyle.ColumnLimit = 80;
65 LLVMStyle.MaxEmptyLinesToKeep = 1;
66 LLVMStyle.PointerAndReferenceBindToType = false;
67 LLVMStyle.AccessModifierOffset = -2;
68 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000069 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000070 return LLVMStyle;
71}
72
73FormatStyle getGoogleStyle() {
74 FormatStyle GoogleStyle;
75 GoogleStyle.ColumnLimit = 80;
76 GoogleStyle.MaxEmptyLinesToKeep = 1;
77 GoogleStyle.PointerAndReferenceBindToType = true;
78 GoogleStyle.AccessModifierOffset = -1;
79 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000080 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000081 return GoogleStyle;
82}
83
84struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000085 unsigned PenaltyIndentLevel;
86};
87
88class UnwrappedLineFormatter {
89public:
90 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
91 const UnwrappedLine &Line,
92 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000093 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000094 : Style(Style), SourceMgr(SourceMgr), Line(Line),
95 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +000096 StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +000097 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperbac016b2012-12-03 18:12:45 +000098 }
99
100 void format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000101 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000102 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000103
104 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000105 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000106 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000107 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000108 State.Indent.push_back(Indent + 4);
109 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000110 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000111 State.ForLoopVariablePos = 0;
112 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000113
114 // The first token has already been indented and thus consumed.
115 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000116
Daniel Jasper1321eb52012-12-18 21:05:13 +0000117 // Check whether the UnwrappedLine can be put onto a single line. If so,
118 // this is bound to be the optimal solution (by definition) and we don't
119 // need to analyze the entire solution space.
120 unsigned Columns = State.Column;
121 bool FitsOnALine = true;
122 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
123 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
124 Line.Tokens[i].Tok.getLength();
125 // A special case for the colon of a constructor initializer as this only
126 // needs to be put on a new line if the line needs to be split.
127 if (Columns > Style.ColumnLimit ||
128 (Annotations[i].MustBreakBefore &&
129 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
130 FitsOnALine = false;
131 break;
132 }
133 }
134
Daniel Jasperbac016b2012-12-03 18:12:45 +0000135 // Start iterating at 1 as we have correctly formatted of Token #0 above.
136 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000137 if (FitsOnALine) {
138 addTokenToState(false, false, State);
139 } else {
140 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
141 unsigned Break = calcPenalty(State, true, NoBreak);
142 addTokenToState(Break < NoBreak, false, State);
143 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000144 }
145 }
146
147private:
148 /// \brief The current state when indenting a unwrapped line.
149 ///
150 /// As the indenting tries different combinations this is copied by value.
151 struct IndentState {
152 /// \brief The number of used columns in the current line.
153 unsigned Column;
154
155 /// \brief The number of tokens already consumed.
156 unsigned ConsumedTokens;
157
158 /// \brief The position to which a specific parenthesis level needs to be
159 /// indented.
160 std::vector<unsigned> Indent;
161
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000162 /// \brief The position of the last space on each level.
163 ///
164 /// Used e.g. to break like:
165 /// functionCall(Parameter, otherCall(
166 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000167 std::vector<unsigned> LastSpace;
168
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000169 /// \brief The position the first "<<" operator encountered on each level.
170 ///
171 /// Used to align "<<" operators. 0 if no such operator has been encountered
172 /// on a level.
173 std::vector<unsigned> FirstLessLess;
174
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000175 /// \brief The column of the first variable in a for-loop declaration.
176 ///
177 /// Used to align the second variable if necessary.
178 unsigned ForLoopVariablePos;
179
180 /// \brief \c true if this line contains a continued for-loop section.
181 bool LineContainsContinuedForLoopSection;
182
Daniel Jasperbac016b2012-12-03 18:12:45 +0000183 /// \brief Comparison operator to be able to used \c IndentState in \c map.
184 bool operator<(const IndentState &Other) const {
185 if (Other.ConsumedTokens != ConsumedTokens)
186 return Other.ConsumedTokens > ConsumedTokens;
187 if (Other.Column != Column)
188 return Other.Column > Column;
189 if (Other.Indent.size() != Indent.size())
190 return Other.Indent.size() > Indent.size();
191 for (int i = 0, e = Indent.size(); i != e; ++i) {
192 if (Other.Indent[i] != Indent[i])
193 return Other.Indent[i] > Indent[i];
194 }
195 if (Other.LastSpace.size() != LastSpace.size())
196 return Other.LastSpace.size() > LastSpace.size();
197 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
198 if (Other.LastSpace[i] != LastSpace[i])
199 return Other.LastSpace[i] > LastSpace[i];
200 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000201 if (Other.FirstLessLess.size() != FirstLessLess.size())
202 return Other.FirstLessLess.size() > FirstLessLess.size();
203 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
204 if (Other.FirstLessLess[i] != FirstLessLess[i])
205 return Other.FirstLessLess[i] > FirstLessLess[i];
206 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000207 if (Other.ForLoopVariablePos != ForLoopVariablePos)
208 return Other.ForLoopVariablePos < ForLoopVariablePos;
209 if (Other.LineContainsContinuedForLoopSection !=
210 LineContainsContinuedForLoopSection)
211 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000212 return false;
213 }
214 };
215
Daniel Jasper20409152012-12-04 14:54:30 +0000216 /// \brief Appends the next token to \p State and updates information
217 /// necessary for indentation.
218 ///
219 /// Puts the token on the current line if \p Newline is \c true and adds a
220 /// line break and necessary indentation otherwise.
221 ///
222 /// If \p DryRun is \c false, also creates and stores the required
223 /// \c Replacement.
224 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000225 unsigned Index = State.ConsumedTokens;
226 const FormatToken &Current = Line.Tokens[Index];
227 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000228 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000229
230 if (Newline) {
231 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000232 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000233 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000234 } else if (Current.Tok.is(tok::lessless) &&
235 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000236 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000237 } else if (ParenLevel != 0 &&
238 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
239 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000240 // Indent and extra 4 spaces after '=' as it continues an expression.
241 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000242 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000243 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
244 Previous.Tok.is(tok::comma)) {
245 State.Column = State.ForLoopVariablePos;
246 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000247 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000248 }
249
250 if (Line.Tokens[0].Tok.is(tok::kw_for))
251 State.LineContainsContinuedForLoopSection =
252 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000253
Daniel Jasperbac016b2012-12-03 18:12:45 +0000254 if (!DryRun)
255 replaceWhitespace(Current, 1, State.Column);
256
Daniel Jaspera88bb452012-12-04 10:50:12 +0000257 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000258 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000259 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
260 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000261 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000262 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000263 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
264 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
265
Daniel Jasperbac016b2012-12-03 18:12:45 +0000266 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
267 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
268 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000269
Daniel Jasperbac016b2012-12-03 18:12:45 +0000270 if (!DryRun)
271 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000272
Daniel Jaspercf225b62012-12-24 13:43:52 +0000273 // FIXME: Look into using this alignment at other ParenLevels.
274 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
275 Previous.Tok.is(tok::kw_return)))
276 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper20409152012-12-04 14:54:30 +0000277 if (Previous.Tok.is(tok::l_paren) ||
278 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000279 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000280
Daniel Jasperbac016b2012-12-03 18:12:45 +0000281 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000282 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000283 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000284 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000285 }
Daniel Jasper20409152012-12-04 14:54:30 +0000286 moveStateToNextToken(State);
287 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000288
Daniel Jasper20409152012-12-04 14:54:30 +0000289 /// \brief Mark the next token as consumed in \p State and modify its stacks
290 /// accordingly.
291 void moveStateToNextToken(IndentState &State) {
292 unsigned Index = State.ConsumedTokens;
293 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000294 unsigned ParenLevel = State.Indent.size() - 1;
295
296 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
297 State.FirstLessLess[ParenLevel] = State.Column;
298
299 State.Column += Current.Tok.getLength();
Daniel Jasper20409152012-12-04 14:54:30 +0000300
Daniel Jaspercf225b62012-12-24 13:43:52 +0000301 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000302 // prepare for the following tokens.
303 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000304 Current.Tok.is(tok::l_brace) ||
Daniel Jasper20409152012-12-04 14:54:30 +0000305 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
306 State.Indent.push_back(4 + State.LastSpace.back());
307 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000308 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000309 }
310
Daniel Jaspercf225b62012-12-24 13:43:52 +0000311 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000312 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000313 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000314 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jaspera88bb452012-12-04 10:50:12 +0000315 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000316 State.Indent.pop_back();
317 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000318 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000319 }
320
321 ++State.ConsumedTokens;
322 }
323
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000324 /// \brief Calculate the panelty for splitting after the token at \p Index.
325 unsigned splitPenalty(unsigned Index) {
326 assert(Index < Line.Tokens.size() &&
327 "Tried to calculate penalty for splitting after the last token");
328 const FormatToken &Left = Line.Tokens[Index];
329 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000330
331 // In for-loops, prefer breaking at ',' and ';'.
332 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
333 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
334 return 20;
335
Daniel Jasper1321eb52012-12-18 21:05:13 +0000336 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000337 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000338 if (Left.Tok.is(tok::l_paren))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000339 return 2;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000340
Daniel Jaspercf225b62012-12-24 13:43:52 +0000341 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000342 if (Level != prec::Unknown)
343 return Level;
344
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000345 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
346 return 200;
347
Daniel Jasperbac016b2012-12-03 18:12:45 +0000348 return 3;
349 }
350
351 /// \brief Calculate the number of lines needed to format the remaining part
352 /// of the unwrapped line.
353 ///
354 /// Assumes the formatting so far has led to
355 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
356 /// added after the previous token.
357 ///
358 /// \param StopAt is used for optimization. If we can determine that we'll
359 /// definitely need at least \p StopAt additional lines, we already know of a
360 /// better solution.
361 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
362 // We are at the end of the unwrapped line, so we don't need any more lines.
363 if (State.ConsumedTokens >= Line.Tokens.size())
364 return 0;
365
366 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
367 return UINT_MAX;
368 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
369 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000370 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
371 State.LineContainsContinuedForLoopSection)
372 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000373
Daniel Jasper33182dd2012-12-05 14:57:28 +0000374 unsigned CurrentPenalty = 0;
375 if (NewLine) {
376 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper1321eb52012-12-18 21:05:13 +0000377 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000378 }
379
Daniel Jasper20409152012-12-04 14:54:30 +0000380 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000381
382 // Exceeding column limit is bad.
383 if (State.Column > Style.ColumnLimit)
384 return UINT_MAX;
385
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386 if (StopAt <= CurrentPenalty)
387 return UINT_MAX;
388 StopAt -= CurrentPenalty;
389
Daniel Jasperbac016b2012-12-03 18:12:45 +0000390 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000391 if (I != Memory.end()) {
392 // If this state has already been examined, we can safely return the
393 // previous result if we
394 // - have not hit the optimatization (and thus returned UINT_MAX) OR
395 // - are now computing for a smaller or equal StopAt.
396 unsigned SavedResult = I->second.first;
397 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000398 if (SavedResult != UINT_MAX)
399 return SavedResult + CurrentPenalty;
400 else if (StopAt <= SavedStopAt)
401 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000402 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000403
404 unsigned NoBreak = calcPenalty(State, false, StopAt);
405 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
406 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000407
408 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
409 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000410 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000411
412 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000413 }
414
415 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
416 /// each \c FormatToken.
417 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
418 unsigned Spaces) {
419 Replaces.insert(tooling::Replacement(
420 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
421 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
422 }
423
424 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000425 /// of the \c UnwrappedLine if there was no structural parsing error.
426 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000427 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000429 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
430 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
431
432 unsigned Newlines =
433 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
434 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
435 if (Newlines == 0 && Offset != 0)
436 Newlines = 1;
437 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000438 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
439 Token.Tok.is(tok::kw_private)) &&
440 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000441 Indent += Style.AccessModifierOffset;
442 replaceWhitespace(Token, Newlines, Indent);
443 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000444 }
445
446 FormatStyle Style;
447 SourceManager &SourceMgr;
448 const UnwrappedLine &Line;
449 const std::vector<TokenAnnotation> &Annotations;
450 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000451 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000452
Daniel Jasper33182dd2012-12-05 14:57:28 +0000453 // A map from an indent state to a pair (Result, Used-StopAt).
454 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
455 StateMap Memory;
456
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457 OptimizationParameters Parameters;
458};
459
460/// \brief Determines extra information about the tokens comprising an
461/// \c UnwrappedLine.
462class TokenAnnotator {
463public:
464 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
465 SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000466 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000467 }
468
469 /// \brief A parser that gathers additional information about tokens.
470 ///
471 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
472 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
473 /// into template parameter lists.
474 class AnnotatingParser {
475 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000476 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000477 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000478 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000479 }
480
Daniel Jasper20409152012-12-04 14:54:30 +0000481 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000482 while (Index < Tokens.size()) {
483 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000484 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000485 next();
486 return true;
487 }
488 if (Tokens[Index].Tok.is(tok::r_paren) ||
489 Tokens[Index].Tok.is(tok::r_square))
490 return false;
491 if (Tokens[Index].Tok.is(tok::pipepipe) ||
492 Tokens[Index].Tok.is(tok::ampamp) ||
493 Tokens[Index].Tok.is(tok::question) ||
494 Tokens[Index].Tok.is(tok::colon))
495 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000496 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000497 }
498 return false;
499 }
500
Daniel Jasper20409152012-12-04 14:54:30 +0000501 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000502 while (Index < Tokens.size()) {
503 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000504 next();
505 return true;
506 }
507 if (Tokens[Index].Tok.is(tok::r_square))
508 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000509 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000510 }
511 return false;
512 }
513
Daniel Jasper20409152012-12-04 14:54:30 +0000514 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000515 while (Index < Tokens.size()) {
516 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000517 next();
518 return true;
519 }
520 if (Tokens[Index].Tok.is(tok::r_paren))
521 return false;
Daniel Jasper20409152012-12-04 14:54:30 +0000522 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 }
524 return false;
525 }
526
Daniel Jasper20409152012-12-04 14:54:30 +0000527 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000528 while (Index < Tokens.size()) {
529 if (Tokens[Index].Tok.is(tok::colon)) {
530 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
531 next();
532 return true;
533 }
Daniel Jasper20409152012-12-04 14:54:30 +0000534 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 }
536 return false;
537 }
538
Daniel Jasper20409152012-12-04 14:54:30 +0000539 void consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000540 unsigned CurrentIndex = Index;
541 next();
542 switch (Tokens[CurrentIndex].Tok.getKind()) {
543 case tok::l_paren:
Daniel Jasper20409152012-12-04 14:54:30 +0000544 parseParens();
Daniel Jasper1321eb52012-12-18 21:05:13 +0000545 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
546 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
547 next();
548 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000549 break;
550 case tok::l_square:
Daniel Jasper20409152012-12-04 14:54:30 +0000551 parseSquare();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000552 break;
553 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000554 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000555 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
556 else {
557 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
558 Index = CurrentIndex + 1;
559 }
560 break;
561 case tok::greater:
562 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
563 break;
564 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000565 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000567 next();
568 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
569 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
570 next();
571 }
572 } else {
573 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
574 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
575 next();
576 }
577 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000578 break;
579 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000580 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000581 break;
582 default:
583 break;
584 }
585 }
586
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000587 void parseIncludeDirective() {
588 while (Index < Tokens.size()) {
589 if (Tokens[Index].Tok.is(tok::slash))
590 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
591 else if (Tokens[Index].Tok.is(tok::less))
592 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
593 else if (Tokens[Index].Tok.is(tok::greater))
594 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
595 next();
596 }
597 }
598
599 void parsePreprocessorDirective() {
600 next();
601 if (Index >= Tokens.size())
602 return;
603 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
604 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000605 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000606 parseIncludeDirective();
607 break;
608 default:
609 break;
610 }
611 }
612
Daniel Jasperbac016b2012-12-03 18:12:45 +0000613 void parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000614 if (Tokens[Index].Tok.is(tok::hash)) {
615 parsePreprocessorDirective();
616 return;
617 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618 while (Index < Tokens.size()) {
Daniel Jasper20409152012-12-04 14:54:30 +0000619 consumeToken();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000620 }
621 }
622
623 void next() {
624 ++Index;
625 }
626
627 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000628 const SmallVector<FormatToken, 16> &Tokens;
629 std::vector<TokenAnnotation> &Annotations;
630 unsigned Index;
631 };
632
633 void annotate() {
634 Annotations.clear();
635 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
636 Annotations.push_back(TokenAnnotation());
637 }
638
Manuel Klimek0be4b362012-12-03 20:55:42 +0000639 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000640 Parser.parseLine();
641
642 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000643 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000644 (Line.Tokens.size() > 0 &&
645 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000646 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
647 TokenAnnotation &Annotation = Annotations[i];
648
649 Annotation.CanBreakBefore =
650 canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]);
651
Daniel Jasper1321eb52012-12-18 21:05:13 +0000652 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
653 Annotation.MustBreakBefore = true;
654 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000655 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
656 Annotation.SpaceRequiredBefore =
657 Line.Tokens[i].Tok.is(tok::identifier) || Line.Tokens[i].Tok.is(
658 tok::kw_new) || Line.Tokens[i].Tok.is(tok::kw_delete);
659 } else if (
660 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
661 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000662 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
663 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
664 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000665 Annotation.CanBreakBefore = true;
666 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000667 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
668 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
669 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000670 // Don't break this identifier as ':' or identifier
671 // before it will break.
672 Annotation.CanBreakBefore = false;
673 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000674 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000675 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000676 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000677 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000678 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000679 Annotation.SpaceRequiredBefore =
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000680 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
681 (i != e - 1);
682 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000683 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
684 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000685 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000686 } else if (
687 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000688 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000689 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000690 Annotation.SpaceRequiredBefore = false;
691 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
692 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000693 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
694 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000695 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
696 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000697 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000698 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000699 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000700 else
701 Annotation.SpaceRequiredBefore = false;
702 } else if (
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000703 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
704 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
705 Annotation.SpaceRequiredBefore = false;
706 } else if (
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
708 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
709 Annotation.SpaceRequiredBefore = true;
710 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000711 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000712 Line.Tokens[i].Tok.is(tok::l_paren)) {
713 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000714 } else if (Line.Tokens[i].Tok.is(tok::less) &&
715 Line.Tokens[0].Tok.is(tok::hash)) {
716 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000717 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
718 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000719 // Don't space between ')' and <id>
720 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000721 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
722 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000723 // Don't space between ':' and '('
724 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000725 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
726 Annotation.SpaceRequiredBefore = false;
727 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000728 Annotation.SpaceRequiredBefore =
729 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
730 }
731
732 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
733 (Line.Tokens[i].Tok.is(tok::string_literal) &&
734 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
735 Annotation.MustBreakBefore = true;
736 }
737
738 if (Annotation.MustBreakBefore)
739 Annotation.CanBreakBefore = true;
740 }
741 }
742
743 const std::vector<TokenAnnotation> &getAnnotations() {
744 return Annotations;
745 }
746
747private:
748 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000749 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000750 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
751 TokenAnnotation &Annotation = Annotations[i];
752 const FormatToken &Tok = Line.Tokens[i];
753
Daniel Jaspercf225b62012-12-24 13:43:52 +0000754 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000755 IsRHS = true;
756 else if (Tok.Tok.is(tok::kw_return))
757 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000758
Daniel Jasper675d2e32012-12-21 10:20:02 +0000759 if (Annotation.Type != TokenAnnotation::TT_Unknown)
760 continue;
761
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000762 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000763 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000764 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
765 Annotation.Type = determinePlusMinusUsage(i);
766 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
767 Annotation.Type = determineIncrementUsage(i);
768 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000769 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000770 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000771 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000772 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000773 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
774 Tok.Tok.getLength());
775 if (Data.startswith("//"))
776 Annotation.Type = TokenAnnotation::TT_LineComment;
777 else
778 Annotation.Type = TokenAnnotation::TT_BlockComment;
779 }
780 }
781 }
782
Daniel Jasperbac016b2012-12-03 18:12:45 +0000783 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000784 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000785 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000786 }
787
Daniel Jasper112fb272012-12-05 07:51:39 +0000788 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index,
Nico Weber00d5a042012-12-23 01:07:46 +0000789 bool IsRHS) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000790 if (Index == Annotations.size())
791 return TokenAnnotation::TT_Unknown;
792
793 if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) ||
794 Line.Tokens[Index - 1].Tok.is(tok::comma) ||
Nico Weber00d5a042012-12-23 01:07:46 +0000795 Line.Tokens[Index - 1].Tok.is(tok::kw_return) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000796 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
797 return TokenAnnotation::TT_UnaryOperator;
798
799 if (Line.Tokens[Index - 1].Tok.isLiteral() ||
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000800 Line.Tokens[Index + 1].Tok.isLiteral() ||
801 Line.Tokens[Index + 1].Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000802 return TokenAnnotation::TT_BinaryOperator;
803
Daniel Jasper112fb272012-12-05 07:51:39 +0000804 // It is very unlikely that we are going to find a pointer or reference type
805 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000806 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000807 return TokenAnnotation::TT_BinaryOperator;
808
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809 return TokenAnnotation::TT_PointerOrReference;
810 }
811
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000812 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
813 // At the start of the line, +/- specific ObjectiveC method declarations.
814 if (Index == 0)
815 return TokenAnnotation::TT_ObjCMethodSpecifier;
816
817 // Use heuristics to recognize unary operators.
818 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
819 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
820 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
821 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon))
822 return TokenAnnotation::TT_UnaryOperator;
823
824 // There can't be to consecutive binary operators.
825 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
826 return TokenAnnotation::TT_UnaryOperator;
827
828 // Fall back to marking the token as binary operator.
829 return TokenAnnotation::TT_BinaryOperator;
830 }
831
832 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
833 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
834 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
835 return TokenAnnotation::TT_TrailingUnaryOperator;
836
837 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000838 }
839
840 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000841 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
842 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000843 if (Left.is(tok::kw_template) && Right.is(tok::less))
844 return true;
845 if (Left.is(tok::arrow) || Right.is(tok::arrow))
846 return false;
847 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
848 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000849 if (Left.is(tok::at) && Right.is(tok::identifier))
850 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000851 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
852 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000853 if (Right.is(tok::amp) || Right.is(tok::star))
854 return Left.isLiteral() ||
855 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
856 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000857 if (Left.is(tok::amp) || Left.is(tok::star))
858 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
859 if (Right.is(tok::star) && Left.is(tok::l_paren))
860 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000861 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
862 Right.is(tok::r_square))
863 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000864 if (Left.is(tok::coloncolon) ||
865 (Right.is(tok::coloncolon) &&
866 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000867 return false;
868 if (Left.is(tok::period) || Right.is(tok::period))
869 return false;
870 if (Left.is(tok::colon) || Right.is(tok::colon))
871 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000872 if (Left.is(tok::l_paren))
873 return false;
874 if (Left.is(tok::hash))
875 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000876 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000877 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
878 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
879 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
880 Left.isNot(tok::kw_typeof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000881 }
882 return true;
883 }
884
885 bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) {
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000886 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
887 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000888 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000889 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
890 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
891 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
892 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
893 Left.Tok.is(tok::l_brace) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000894 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
895 }
896
897 const UnwrappedLine &Line;
898 FormatStyle Style;
899 SourceManager &SourceMgr;
900 std::vector<TokenAnnotation> Annotations;
901};
902
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000903class LexerBasedFormatTokenSource : public FormatTokenSource {
904public:
905 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000906 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000907 IdentTable(Lex.getLangOpts()) {
908 Lex.SetKeepWhitespaceMode(true);
909 }
910
911 virtual FormatToken getNextToken() {
912 if (GreaterStashed) {
913 FormatTok.NewlinesBefore = 0;
914 FormatTok.WhiteSpaceStart =
915 FormatTok.Tok.getLocation().getLocWithOffset(1);
916 FormatTok.WhiteSpaceLength = 0;
917 GreaterStashed = false;
918 return FormatTok;
919 }
920
921 FormatTok = FormatToken();
922 Lex.LexFromRawLexer(FormatTok.Tok);
923 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
924
925 // Consume and record whitespace until we find a significant token.
926 while (FormatTok.Tok.is(tok::unknown)) {
927 FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n');
928 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
929
930 if (FormatTok.Tok.is(tok::eof))
931 return FormatTok;
932 Lex.LexFromRawLexer(FormatTok.Tok);
933 }
934
935 if (FormatTok.Tok.is(tok::raw_identifier)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000936 IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok));
937 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000938 FormatTok.Tok.setKind(Info.getTokenID());
939 }
940
941 if (FormatTok.Tok.is(tok::greatergreater)) {
942 FormatTok.Tok.setKind(tok::greater);
943 GreaterStashed = true;
944 }
945
946 return FormatTok;
947 }
948
949private:
950 FormatToken FormatTok;
951 bool GreaterStashed;
952 Lexer &Lex;
953 SourceManager &SourceMgr;
954 IdentifierTable IdentTable;
955
956 /// Returns the text of \c FormatTok.
957 StringRef tokenText(Token &Tok) {
958 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
959 Tok.getLength());
960 }
961};
962
Daniel Jasperbac016b2012-12-03 18:12:45 +0000963class Formatter : public UnwrappedLineConsumer {
964public:
965 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
966 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000967 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000968 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000969 }
970
Daniel Jasperaccb0b02012-12-04 21:05:31 +0000971 virtual ~Formatter() {
972 }
973
Daniel Jasperbac016b2012-12-03 18:12:45 +0000974 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +0000975 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
976 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000977 StructuralError = Parser.parse();
978 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
979 E = UnwrappedLines.end();
980 I != E; ++I)
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000981 formatUnwrappedLine(*I);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000982 return Replaces;
983 }
984
985private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000986 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000987 UnwrappedLines.push_back(TheLine);
988 }
989
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000990 void formatUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000991 if (TheLine.Tokens.size() == 0)
992 return;
993
994 CharSourceRange LineRange =
995 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
996 TheLine.Tokens.back().Tok.getLocation());
997
998 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
999 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1000 Ranges[i].getBegin()) ||
1001 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1002 LineRange.getBegin()))
1003 continue;
1004
1005 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
1006 Annotator.annotate();
1007 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine,
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001008 Annotator.getAnnotations(), Replaces,
1009 StructuralError);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001010 Formatter.format();
1011 return;
1012 }
1013 }
1014
1015 FormatStyle Style;
1016 Lexer &Lex;
1017 SourceManager &SourceMgr;
1018 tooling::Replacements Replaces;
1019 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001020 std::vector<UnwrappedLine> UnwrappedLines;
1021 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001022};
1023
1024tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1025 SourceManager &SourceMgr,
1026 std::vector<CharSourceRange> Ranges) {
1027 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1028 return formatter.format();
1029}
1030
1031} // namespace format
1032} // namespace clang