blob: 7b3c575d0b179c8892c72986741f079643d88148 [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 Jasper675d2e32012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperbac016b2012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
29// FIXME: Move somewhere sane.
30struct TokenAnnotation {
Daniel Jasper33182dd2012-12-05 14:57:28 +000031 enum TokenType {
32 TT_Unknown,
33 TT_TemplateOpener,
34 TT_TemplateCloser,
35 TT_BinaryOperator,
36 TT_UnaryOperator,
Daniel Jasper98e6b4a2012-12-21 09:41:31 +000037 TT_TrailingUnaryOperator,
Daniel Jasper33182dd2012-12-05 14:57:28 +000038 TT_OverloadedOperator,
39 TT_PointerOrReference,
40 TT_ConditionalExpr,
Daniel Jasper1321eb52012-12-18 21:05:13 +000041 TT_CtorInitializerColon,
Daniel Jasper33182dd2012-12-05 14:57:28 +000042 TT_LineComment,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000043 TT_BlockComment,
Daniel Jaspercd1a32b2012-12-21 17:58:39 +000044 TT_DirectorySeparator,
Fariborz Jahanian154120c2012-12-20 19:54:13 +000045 TT_ObjCMethodSpecifier
Daniel Jasper33182dd2012-12-05 14:57:28 +000046 };
Daniel Jasperbac016b2012-12-03 18:12:45 +000047
48 TokenType Type;
49
Daniel Jasperbac016b2012-12-03 18:12:45 +000050 bool SpaceRequiredBefore;
51 bool CanBreakBefore;
52 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000053
54 bool ClosesTemplateDeclaration;
Daniel Jasperbac016b2012-12-03 18:12:45 +000055};
56
Daniel Jaspercf225b62012-12-24 13:43:52 +000057static prec::Level getPrecedence(const FormatToken &Tok) {
58 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
59}
60
Daniel Jasperbac016b2012-12-03 18:12:45 +000061using llvm::MutableArrayRef;
62
63FormatStyle getLLVMStyle() {
64 FormatStyle LLVMStyle;
65 LLVMStyle.ColumnLimit = 80;
66 LLVMStyle.MaxEmptyLinesToKeep = 1;
67 LLVMStyle.PointerAndReferenceBindToType = false;
68 LLVMStyle.AccessModifierOffset = -2;
69 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000070 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +000071 return LLVMStyle;
72}
73
74FormatStyle getGoogleStyle() {
75 FormatStyle GoogleStyle;
76 GoogleStyle.ColumnLimit = 80;
77 GoogleStyle.MaxEmptyLinesToKeep = 1;
78 GoogleStyle.PointerAndReferenceBindToType = true;
79 GoogleStyle.AccessModifierOffset = -1;
80 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000081 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +000082 return GoogleStyle;
83}
84
85struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000086 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +000087 unsigned PenaltyLevelDecrease;
Daniel Jasperbac016b2012-12-03 18:12:45 +000088};
89
90class UnwrappedLineFormatter {
91public:
92 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
93 const UnwrappedLine &Line,
Manuel Klimekd4397b92013-01-04 23:34:14 +000094 unsigned PreviousEndOfLineColumn,
Daniel Jasperbac016b2012-12-03 18:12:45 +000095 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +000096 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +000097 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekd4397b92013-01-04 23:34:14 +000098 PreviousEndOfLineColumn(PreviousEndOfLineColumn),
Daniel Jasper1321eb52012-12-18 21:05:13 +000099 Annotations(Annotations), Replaces(Replaces),
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000100 StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000101 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000102 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000103 }
104
Manuel Klimekd4397b92013-01-04 23:34:14 +0000105 /// \brief Formats an \c UnwrappedLine.
106 ///
107 /// \returns The column after the last token in the last line of the
108 /// \c UnwrappedLine.
109 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000110 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000111 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000112
113 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000114 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000115 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000116 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000117 State.Indent.push_back(Indent + 4);
118 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000119 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000120 State.ForLoopVariablePos = 0;
121 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000122 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000123
124 // The first token has already been indented and thus consumed.
125 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000126
Daniel Jasper1321eb52012-12-18 21:05:13 +0000127 // Check whether the UnwrappedLine can be put onto a single line. If so,
128 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasper1f42f112013-01-04 18:52:56 +0000129 // need to analyze the entire solution space.
Daniel Jasper1321eb52012-12-18 21:05:13 +0000130 unsigned Columns = State.Column;
131 bool FitsOnALine = true;
132 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
133 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
Manuel Klimek95419382013-01-07 07:56:50 +0000134 Line.Tokens[i].TokenLength;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000135 // A special case for the colon of a constructor initializer as this only
136 // needs to be put on a new line if the line needs to be split.
Manuel Klimek95419382013-01-07 07:56:50 +0000137 // FIXME: We need to check whether we're in a preprocessor directive, even
138 // if all tokens fit - the next line might be a preprocessor directive,
139 // too, in which case we need to account for the possible escaped newline.
Manuel Klimekd544c572013-01-07 09:24:17 +0000140 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper1321eb52012-12-18 21:05:13 +0000141 (Annotations[i].MustBreakBefore &&
142 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
143 FitsOnALine = false;
144 break;
145 }
146 }
147
Daniel Jasperbac016b2012-12-03 18:12:45 +0000148 // Start iterating at 1 as we have correctly formatted of Token #0 above.
149 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000150 if (FitsOnALine) {
151 addTokenToState(false, false, State);
152 } else {
153 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
154 unsigned Break = calcPenalty(State, true, NoBreak);
155 addTokenToState(Break < NoBreak, false, State);
156 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000157 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000158 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000159 }
160
161private:
162 /// \brief The current state when indenting a unwrapped line.
163 ///
164 /// As the indenting tries different combinations this is copied by value.
165 struct IndentState {
166 /// \brief The number of used columns in the current line.
167 unsigned Column;
168
169 /// \brief The number of tokens already consumed.
170 unsigned ConsumedTokens;
171
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000172 /// \brief The parenthesis level of the first token on the current line.
173 unsigned StartOfLineLevel;
174
Daniel Jasperbac016b2012-12-03 18:12:45 +0000175 /// \brief The position to which a specific parenthesis level needs to be
176 /// indented.
177 std::vector<unsigned> Indent;
178
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000179 /// \brief The position of the last space on each level.
180 ///
181 /// Used e.g. to break like:
182 /// functionCall(Parameter, otherCall(
183 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000184 std::vector<unsigned> LastSpace;
185
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000186 /// \brief The position the first "<<" operator encountered on each level.
187 ///
188 /// Used to align "<<" operators. 0 if no such operator has been encountered
189 /// on a level.
190 std::vector<unsigned> FirstLessLess;
191
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000192 /// \brief The column of the first variable in a for-loop declaration.
193 ///
194 /// Used to align the second variable if necessary.
195 unsigned ForLoopVariablePos;
196
197 /// \brief \c true if this line contains a continued for-loop section.
198 bool LineContainsContinuedForLoopSection;
199
Daniel Jasperbac016b2012-12-03 18:12:45 +0000200 /// \brief Comparison operator to be able to used \c IndentState in \c map.
201 bool operator<(const IndentState &Other) const {
202 if (Other.ConsumedTokens != ConsumedTokens)
203 return Other.ConsumedTokens > ConsumedTokens;
204 if (Other.Column != Column)
205 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000206 if (Other.StartOfLineLevel != StartOfLineLevel)
207 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000208 if (Other.Indent.size() != Indent.size())
209 return Other.Indent.size() > Indent.size();
210 for (int i = 0, e = Indent.size(); i != e; ++i) {
211 if (Other.Indent[i] != Indent[i])
212 return Other.Indent[i] > Indent[i];
213 }
214 if (Other.LastSpace.size() != LastSpace.size())
215 return Other.LastSpace.size() > LastSpace.size();
216 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
217 if (Other.LastSpace[i] != LastSpace[i])
218 return Other.LastSpace[i] > LastSpace[i];
219 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000220 if (Other.FirstLessLess.size() != FirstLessLess.size())
221 return Other.FirstLessLess.size() > FirstLessLess.size();
222 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
223 if (Other.FirstLessLess[i] != FirstLessLess[i])
224 return Other.FirstLessLess[i] > FirstLessLess[i];
225 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000226 if (Other.ForLoopVariablePos != ForLoopVariablePos)
227 return Other.ForLoopVariablePos < ForLoopVariablePos;
228 if (Other.LineContainsContinuedForLoopSection !=
229 LineContainsContinuedForLoopSection)
230 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000231 return false;
232 }
233 };
234
Daniel Jasper20409152012-12-04 14:54:30 +0000235 /// \brief Appends the next token to \p State and updates information
236 /// necessary for indentation.
237 ///
238 /// Puts the token on the current line if \p Newline is \c true and adds a
239 /// line break and necessary indentation otherwise.
240 ///
241 /// If \p DryRun is \c false, also creates and stores the required
242 /// \c Replacement.
243 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000244 unsigned Index = State.ConsumedTokens;
245 const FormatToken &Current = Line.Tokens[Index];
246 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000247 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000248
249 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000250 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000251 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000252 Previous.Tok.is(tok::string_literal)) {
Manuel Klimek95419382013-01-07 07:56:50 +0000253 State.Column = State.Column - Previous.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000254 } else if (Current.Tok.is(tok::lessless) &&
255 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000256 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000257 } else if (ParenLevel != 0 &&
258 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
259 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000260 // Indent and extra 4 spaces after '=' as it continues an expression.
261 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000262 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasperd7610b82012-12-24 16:51:15 +0000263 } else if (
264 Line.Tokens[0].Tok.is(tok::kw_for) && Previous.Tok.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000265 State.Column = State.ForLoopVariablePos;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000266 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
267 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000268 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000269 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000270 }
271
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000272 State.StartOfLineLevel = ParenLevel + 1;
273
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000274 if (Line.Tokens[0].Tok.is(tok::kw_for))
275 State.LineContainsContinuedForLoopSection =
276 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000277
Manuel Klimek060143e2013-01-02 18:33:23 +0000278 if (!DryRun) {
279 if (!Line.InPPDirective)
280 replaceWhitespace(Current, 1, State.Column);
281 else
282 replacePPWhitespace(Current, 1, State.Column, WhitespaceStartColumn);
283 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000284
Daniel Jaspera88bb452012-12-04 10:50:12 +0000285 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000286 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000287 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
288 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000289 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000290 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000291 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
Manuel Klimek95419382013-01-07 07:56:50 +0000292 State.ForLoopVariablePos = State.Column - Previous.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000293
Daniel Jasperbac016b2012-12-03 18:12:45 +0000294 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
295 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
296 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000297
Daniel Jasperbac016b2012-12-03 18:12:45 +0000298 if (!DryRun)
299 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000300
Daniel Jaspercf225b62012-12-24 13:43:52 +0000301 // FIXME: Look into using this alignment at other ParenLevels.
302 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
303 Previous.Tok.is(tok::kw_return)))
304 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper20409152012-12-04 14:54:30 +0000305 if (Previous.Tok.is(tok::l_paren) ||
306 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000308
Daniel Jasperbac016b2012-12-03 18:12:45 +0000309 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000310 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000311 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000312 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000313 }
Daniel Jasper20409152012-12-04 14:54:30 +0000314 moveStateToNextToken(State);
315 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000316
Daniel Jasper20409152012-12-04 14:54:30 +0000317 /// \brief Mark the next token as consumed in \p State and modify its stacks
318 /// accordingly.
319 void moveStateToNextToken(IndentState &State) {
320 unsigned Index = State.ConsumedTokens;
321 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000322 unsigned ParenLevel = State.Indent.size() - 1;
323
324 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
325 State.FirstLessLess[ParenLevel] = State.Column;
326
Manuel Klimek95419382013-01-07 07:56:50 +0000327 State.Column += Current.TokenLength;
Daniel Jasper20409152012-12-04 14:54:30 +0000328
Daniel Jaspercf225b62012-12-24 13:43:52 +0000329 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000330 // prepare for the following tokens.
331 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000332 Current.Tok.is(tok::l_brace) ||
Daniel Jasper20409152012-12-04 14:54:30 +0000333 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
334 State.Indent.push_back(4 + State.LastSpace.back());
335 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000336 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000337 }
338
Daniel Jaspercf225b62012-12-24 13:43:52 +0000339 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000340 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000341 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000342 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jaspera88bb452012-12-04 10:50:12 +0000343 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000344 State.Indent.pop_back();
345 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000346 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000347 }
348
349 ++State.ConsumedTokens;
350 }
351
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000352 /// \brief Calculate the panelty for splitting after the token at \p Index.
353 unsigned splitPenalty(unsigned Index) {
354 assert(Index < Line.Tokens.size() &&
355 "Tried to calculate penalty for splitting after the last token");
356 const FormatToken &Left = Line.Tokens[Index];
357 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000358
359 // In for-loops, prefer breaking at ',' and ';'.
360 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
361 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
362 return 20;
363
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000364 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
365 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000366 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000367 if (Left.Tok.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000368 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000369
Daniel Jaspercf225b62012-12-24 13:43:52 +0000370 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000371 if (Level != prec::Unknown)
372 return Level;
373
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000374 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000375 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000376
Daniel Jasperbac016b2012-12-03 18:12:45 +0000377 return 3;
378 }
379
380 /// \brief Calculate the number of lines needed to format the remaining part
381 /// of the unwrapped line.
382 ///
383 /// Assumes the formatting so far has led to
384 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
385 /// added after the previous token.
386 ///
387 /// \param StopAt is used for optimization. If we can determine that we'll
388 /// definitely need at least \p StopAt additional lines, we already know of a
389 /// better solution.
390 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
391 // We are at the end of the unwrapped line, so we don't need any more lines.
392 if (State.ConsumedTokens >= Line.Tokens.size())
393 return 0;
394
395 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
396 return UINT_MAX;
397 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
398 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000399 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
400 State.LineContainsContinuedForLoopSection)
401 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000402
Daniel Jasper33182dd2012-12-05 14:57:28 +0000403 unsigned CurrentPenalty = 0;
404 if (NewLine) {
405 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperd7610b82012-12-24 16:51:15 +0000406 splitPenalty(State.ConsumedTokens - 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000407 } else {
408 if (State.Indent.size() < State.StartOfLineLevel)
409 CurrentPenalty += Parameters.PenaltyLevelDecrease *
410 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000411 }
412
Daniel Jasper20409152012-12-04 14:54:30 +0000413 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000414
415 // Exceeding column limit is bad.
Manuel Klimek060143e2013-01-02 18:33:23 +0000416 if (State.Column > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000417 return UINT_MAX;
418
Daniel Jasperbac016b2012-12-03 18:12:45 +0000419 if (StopAt <= CurrentPenalty)
420 return UINT_MAX;
421 StopAt -= CurrentPenalty;
422
Daniel Jasperbac016b2012-12-03 18:12:45 +0000423 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000424 if (I != Memory.end()) {
425 // If this state has already been examined, we can safely return the
426 // previous result if we
427 // - have not hit the optimatization (and thus returned UINT_MAX) OR
428 // - are now computing for a smaller or equal StopAt.
429 unsigned SavedResult = I->second.first;
430 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000431 if (SavedResult != UINT_MAX)
432 return SavedResult + CurrentPenalty;
433 else if (StopAt <= SavedStopAt)
434 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000435 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000436
437 unsigned NoBreak = calcPenalty(State, false, StopAt);
438 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
439 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000440
441 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
442 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000443 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000444
445 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000446 }
447
448 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
449 /// each \c FormatToken.
450 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
451 unsigned Spaces) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000452 Replaces.insert(tooling::Replacement(
453 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
454 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
455 }
456
457 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
458 /// backslashes to escape newlines inside a preprocessor directive.
459 ///
460 /// This function and \c replaceWhitespace have the same behavior if
461 /// \c Newlines == 0.
462 void replacePPWhitespace(const FormatToken &Tok, unsigned NewLines,
463 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000464 std::string NewLineText;
Manuel Klimek060143e2013-01-02 18:33:23 +0000465 if (NewLines > 0) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000466 unsigned Offset =
Manuel Klimek060143e2013-01-02 18:33:23 +0000467 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Manuel Klimeka080a182013-01-02 16:30:12 +0000468 for (unsigned i = 0; i < NewLines; ++i) {
469 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
470 NewLineText += "\\\n";
471 Offset = 0;
472 }
473 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000474 Replaces.insert(tooling::Replacement(
475 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
Manuel Klimeka080a182013-01-02 16:30:12 +0000476 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000477 }
478
479 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000480 /// of the \c UnwrappedLine if there was no structural parsing error.
481 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000482 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000483 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000484 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
485 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
486
487 unsigned Newlines =
488 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000489 if (Newlines == 0 && !Token.IsFirst)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000490 Newlines = 1;
491 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000492 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
493 Token.Tok.is(tok::kw_private)) &&
494 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000495 Indent += Style.AccessModifierOffset;
Manuel Klimek060143e2013-01-02 18:33:23 +0000496 if (!Line.InPPDirective || Token.HasUnescapedNewline)
497 replaceWhitespace(Token, Newlines, Indent);
498 else
Manuel Klimekd4397b92013-01-04 23:34:14 +0000499 replacePPWhitespace(Token, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000500 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501 }
502
503 FormatStyle Style;
504 SourceManager &SourceMgr;
505 const UnwrappedLine &Line;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000506 const unsigned PreviousEndOfLineColumn;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000507 const std::vector<TokenAnnotation> &Annotations;
508 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000509 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000510
Daniel Jasper33182dd2012-12-05 14:57:28 +0000511 // A map from an indent state to a pair (Result, Used-StopAt).
512 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
513 StateMap Memory;
514
Daniel Jasperbac016b2012-12-03 18:12:45 +0000515 OptimizationParameters Parameters;
516};
517
518/// \brief Determines extra information about the tokens comprising an
519/// \c UnwrappedLine.
520class TokenAnnotator {
521public:
522 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000523 SourceManager &SourceMgr, Lexer &Lex)
524 : Line(Line), Style(Style), SourceMgr(SourceMgr), Lex(Lex) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000525 }
526
527 /// \brief A parser that gathers additional information about tokens.
528 ///
529 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
530 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
531 /// into template parameter lists.
532 class AnnotatingParser {
533 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000534 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000536 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000537 }
538
Daniel Jasper20409152012-12-04 14:54:30 +0000539 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000540 while (Index < Tokens.size()) {
541 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000542 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000543 next();
544 return true;
545 }
546 if (Tokens[Index].Tok.is(tok::r_paren) ||
Daniel Jasper1f42f112013-01-04 18:52:56 +0000547 Tokens[Index].Tok.is(tok::r_square) ||
548 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000549 return false;
550 if (Tokens[Index].Tok.is(tok::pipepipe) ||
551 Tokens[Index].Tok.is(tok::ampamp) ||
552 Tokens[Index].Tok.is(tok::question) ||
553 Tokens[Index].Tok.is(tok::colon))
554 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000555 if (!consumeToken())
556 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000557 }
558 return false;
559 }
560
Daniel Jasper20409152012-12-04 14:54:30 +0000561 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000562 while (Index < Tokens.size()) {
563 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000564 next();
565 return true;
566 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000567 if (Tokens[Index].Tok.is(tok::r_square) ||
568 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000569 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000570 if (!consumeToken())
571 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 }
573 return false;
574 }
575
Daniel Jasper20409152012-12-04 14:54:30 +0000576 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000577 while (Index < Tokens.size()) {
578 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000579 next();
580 return true;
581 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000582 if (Tokens[Index].Tok.is(tok::r_paren) ||
583 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000584 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000585 if (!consumeToken())
586 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000587 }
588 return false;
589 }
590
Daniel Jasper20409152012-12-04 14:54:30 +0000591 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 while (Index < Tokens.size()) {
593 if (Tokens[Index].Tok.is(tok::colon)) {
594 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
595 next();
596 return true;
597 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000598 if (!consumeToken())
599 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000600 }
601 return false;
602 }
603
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000604 bool parseTemplateDeclaration() {
605 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
606 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
607 next();
608 if (!parseAngle())
609 return false;
610 Annotations[Index - 1].ClosesTemplateDeclaration = true;
611 parseLine();
612 return true;
613 }
614 return false;
615 }
616
Daniel Jasper1f42f112013-01-04 18:52:56 +0000617 bool consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618 unsigned CurrentIndex = Index;
619 next();
620 switch (Tokens[CurrentIndex].Tok.getKind()) {
621 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000622 if (!parseParens())
623 return false;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000624 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
625 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
626 next();
627 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000628 break;
629 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000630 if (!parseSquare())
631 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000632 break;
633 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000634 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000635 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
636 else {
637 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
638 Index = CurrentIndex + 1;
639 }
640 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000641 case tok::r_paren:
642 case tok::r_square:
643 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000644 case tok::greater:
645 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
646 break;
647 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000648 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000649 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000650 next();
651 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
652 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
653 next();
654 }
655 } else {
656 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
657 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
658 next();
659 }
660 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000661 break;
662 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000663 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000664 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000665 case tok::kw_template:
666 parseTemplateDeclaration();
667 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000668 default:
669 break;
670 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000671 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000672 }
673
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000674 void parseIncludeDirective() {
675 while (Index < Tokens.size()) {
676 if (Tokens[Index].Tok.is(tok::slash))
677 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
678 else if (Tokens[Index].Tok.is(tok::less))
679 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
680 else if (Tokens[Index].Tok.is(tok::greater))
681 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
682 next();
683 }
684 }
685
686 void parsePreprocessorDirective() {
687 next();
688 if (Index >= Tokens.size())
689 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000690 // Hashes in the middle of a line can lead to any strange token
691 // sequence.
692 if (Tokens[Index].Tok.getIdentifierInfo() == NULL)
693 return;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000694 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
695 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000696 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000697 parseIncludeDirective();
698 break;
699 default:
700 break;
701 }
702 }
703
Daniel Jasper1f42f112013-01-04 18:52:56 +0000704 bool parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000705 if (Tokens[Index].Tok.is(tok::hash)) {
706 parsePreprocessorDirective();
Daniel Jasper1f42f112013-01-04 18:52:56 +0000707 return true;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000708 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000709 while (Index < Tokens.size()) {
Daniel Jasper1f42f112013-01-04 18:52:56 +0000710 if (!consumeToken())
711 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000712 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000713 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714 }
715
716 void next() {
717 ++Index;
718 }
719
720 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000721 const SmallVector<FormatToken, 16> &Tokens;
722 std::vector<TokenAnnotation> &Annotations;
723 unsigned Index;
724 };
725
Daniel Jasper1f42f112013-01-04 18:52:56 +0000726 bool annotate() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000727 Annotations.clear();
728 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
729 Annotations.push_back(TokenAnnotation());
730 }
731
Manuel Klimek0be4b362012-12-03 20:55:42 +0000732 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000733 if (!Parser.parseLine())
734 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000735
736 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000737 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000738 (Line.Tokens.size() > 0 &&
739 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000740 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
741 TokenAnnotation &Annotation = Annotations[i];
742
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000743 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000744
Daniel Jasper1321eb52012-12-18 21:05:13 +0000745 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
746 Annotation.MustBreakBefore = true;
747 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000748 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
749 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-12-24 16:51:15 +0000750 Line.Tokens[i].Tok.is(tok::identifier) ||
751 Line.Tokens[i].Tok.is(tok::kw_new) ||
752 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000753 } else if (
754 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
755 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000756 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
757 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
758 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000759 Annotation.CanBreakBefore = true;
760 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000761 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
762 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
763 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000764 // Don't break this identifier as ':' or identifier
765 // before it will break.
766 Annotation.CanBreakBefore = false;
767 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000768 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000769 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000770 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000771 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000772 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000773 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-12-24 16:51:15 +0000774 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
775 (i != e - 1);
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000776 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000777 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
778 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000779 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000780 } else if (
781 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000782 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000783 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000784 Annotation.SpaceRequiredBefore = false;
785 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
786 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000787 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
788 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000789 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
790 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000791 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000792 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000793 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000794 else
795 Annotation.SpaceRequiredBefore = false;
796 } else if (
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000797 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
798 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
799 Annotation.SpaceRequiredBefore = false;
800 } else if (
Daniel Jasperbac016b2012-12-03 18:12:45 +0000801 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
802 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
803 Annotation.SpaceRequiredBefore = true;
804 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000805 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000806 Line.Tokens[i].Tok.is(tok::l_paren)) {
807 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000808 } else if (Line.Tokens[i].Tok.is(tok::less) &&
809 Line.Tokens[0].Tok.is(tok::hash)) {
810 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000811 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
812 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000813 // Don't space between ')' and <id>
814 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000815 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
816 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000817 // Don't space between ':' and '('
818 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000819 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
820 Annotation.SpaceRequiredBefore = false;
821 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000822 Annotation.SpaceRequiredBefore =
823 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
824 }
825
826 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
827 (Line.Tokens[i].Tok.is(tok::string_literal) &&
828 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
829 Annotation.MustBreakBefore = true;
830 }
831
832 if (Annotation.MustBreakBefore)
833 Annotation.CanBreakBefore = true;
834 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000835 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000836 }
837
838 const std::vector<TokenAnnotation> &getAnnotations() {
839 return Annotations;
840 }
841
842private:
843 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000844 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000845 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
846 TokenAnnotation &Annotation = Annotations[i];
847 const FormatToken &Tok = Line.Tokens[i];
848
Daniel Jaspercf225b62012-12-24 13:43:52 +0000849 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000850 IsRHS = true;
851 else if (Tok.Tok.is(tok::kw_return))
852 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000853
Daniel Jasper675d2e32012-12-21 10:20:02 +0000854 if (Annotation.Type != TokenAnnotation::TT_Unknown)
855 continue;
856
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000857 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000858 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000859 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
860 Annotation.Type = determinePlusMinusUsage(i);
861 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
862 Annotation.Type = determineIncrementUsage(i);
863 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000864 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000865 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000866 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000867 } else if (Tok.Tok.is(tok::comment)) {
Manuel Klimek6cf58142013-01-07 08:54:53 +0000868 std::string Data(
869 Lexer::getSpelling(Tok.Tok, SourceMgr, Lex.getLangOpts()));
870 if (StringRef(Data).startswith("//"))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000871 Annotation.Type = TokenAnnotation::TT_LineComment;
872 else
873 Annotation.Type = TokenAnnotation::TT_BlockComment;
874 }
875 }
876 }
877
Daniel Jasperbac016b2012-12-03 18:12:45 +0000878 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000879 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000880 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000881 }
882
Daniel Jasperd7610b82012-12-24 16:51:15 +0000883 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperba3d3072013-01-02 17:21:36 +0000884 if (Index == 0)
885 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000886 if (Index == Annotations.size())
887 return TokenAnnotation::TT_Unknown;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000888 const FormatToken &PrevToken = Line.Tokens[Index - 1];
889 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000890
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000891 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
892 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
893 PrevToken.Tok.is(tok::colon) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000894 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
895 return TokenAnnotation::TT_UnaryOperator;
896
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000897 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000898 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
899 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
900 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
901 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000902 return TokenAnnotation::TT_BinaryOperator;
903
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000904 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
905 NextToken.Tok.is(tok::greater))
906 return TokenAnnotation::TT_PointerOrReference;
907
Daniel Jasper112fb272012-12-05 07:51:39 +0000908 // It is very unlikely that we are going to find a pointer or reference type
909 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000910 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000911 return TokenAnnotation::TT_BinaryOperator;
912
Daniel Jasperbac016b2012-12-03 18:12:45 +0000913 return TokenAnnotation::TT_PointerOrReference;
914 }
915
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000916 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
917 // At the start of the line, +/- specific ObjectiveC method declarations.
918 if (Index == 0)
919 return TokenAnnotation::TT_ObjCMethodSpecifier;
920
921 // Use heuristics to recognize unary operators.
922 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
923 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
924 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasper1f0754b2013-01-02 15:26:16 +0000925 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
926 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000927 return TokenAnnotation::TT_UnaryOperator;
928
929 // There can't be to consecutive binary operators.
930 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
931 return TokenAnnotation::TT_UnaryOperator;
932
933 // Fall back to marking the token as binary operator.
934 return TokenAnnotation::TT_BinaryOperator;
935 }
936
937 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
938 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
939 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
940 return TokenAnnotation::TT_TrailingUnaryOperator;
941
942 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000943 }
944
945 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000946 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
947 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000948 if (Left.is(tok::kw_template) && Right.is(tok::less))
949 return true;
950 if (Left.is(tok::arrow) || Right.is(tok::arrow))
951 return false;
952 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
953 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000954 if (Left.is(tok::at) && Right.is(tok::identifier))
955 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000956 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
957 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000958 if (Right.is(tok::amp) || Right.is(tok::star))
959 return Left.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000960 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
961 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000962 if (Left.is(tok::amp) || Left.is(tok::star))
963 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
964 if (Right.is(tok::star) && Left.is(tok::l_paren))
965 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000966 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
967 Right.is(tok::r_square))
968 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000969 if (Left.is(tok::coloncolon) ||
970 (Right.is(tok::coloncolon) &&
971 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000972 return false;
973 if (Left.is(tok::period) || Right.is(tok::period))
974 return false;
975 if (Left.is(tok::colon) || Right.is(tok::colon))
976 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000977 if (Left.is(tok::l_paren))
978 return false;
979 if (Left.is(tok::hash))
980 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000981 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000982 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000983 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
984 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasperba3d3072013-01-02 17:21:36 +0000985 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000986 }
987 return true;
988 }
989
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000990 bool canBreakBefore(unsigned i) {
Daniel Jasper5eda31e2013-01-02 18:30:06 +0000991 if (Annotations[i - 1].ClosesTemplateDeclaration)
992 return true;
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000993 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
Daniel Jasper5eda31e2013-01-02 18:30:06 +0000994 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser ||
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000995 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
996 return false;
997 }
998 const FormatToken &Left = Line.Tokens[i - 1];
999 const FormatToken &Right = Line.Tokens[i];
Daniel Jasper05b1ac82012-12-17 11:29:41 +00001000 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
1001 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001002 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +00001003 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001004 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
1005 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
1006 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
1007 Left.Tok.is(tok::l_brace) ||
1008 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001009 }
1010
1011 const UnwrappedLine &Line;
1012 FormatStyle Style;
1013 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001014 Lexer &Lex;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001015 std::vector<TokenAnnotation> Annotations;
1016};
1017
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001018class LexerBasedFormatTokenSource : public FormatTokenSource {
1019public:
1020 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001021 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001022 IdentTable(Lex.getLangOpts()) {
1023 Lex.SetKeepWhitespaceMode(true);
1024 }
1025
1026 virtual FormatToken getNextToken() {
1027 if (GreaterStashed) {
1028 FormatTok.NewlinesBefore = 0;
1029 FormatTok.WhiteSpaceStart =
1030 FormatTok.Tok.getLocation().getLocWithOffset(1);
1031 FormatTok.WhiteSpaceLength = 0;
1032 GreaterStashed = false;
1033 return FormatTok;
1034 }
1035
1036 FormatTok = FormatToken();
1037 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001038 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001039 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001040 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1041 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001042
1043 // Consume and record whitespace until we find a significant token.
1044 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001045 FormatTok.NewlinesBefore += Text.count('\n');
1046 FormatTok.HasUnescapedNewline =
1047 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001048 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1049
1050 if (FormatTok.Tok.is(tok::eof))
1051 return FormatTok;
1052 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001053 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001054 }
Manuel Klimek95419382013-01-07 07:56:50 +00001055
1056 // Now FormatTok is the next non-whitespace token.
1057 FormatTok.TokenLength = Text.size();
1058
Manuel Klimekd4397b92013-01-04 23:34:14 +00001059 // In case the token starts with escaped newlines, we want to
1060 // take them into account as whitespace - this pattern is quite frequent
1061 // in macro definitions.
1062 // FIXME: What do we want to do with other escaped spaces, and escaped
1063 // spaces or newlines in the middle of tokens?
1064 // FIXME: Add a more explicit test.
1065 unsigned i = 0;
1066 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i+1] == '\n') {
1067 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001068 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001069 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001070 }
1071
1072 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001073 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001074 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001075 FormatTok.Tok.setKind(Info.getTokenID());
1076 }
1077
1078 if (FormatTok.Tok.is(tok::greatergreater)) {
1079 FormatTok.Tok.setKind(tok::greater);
1080 GreaterStashed = true;
1081 }
1082
1083 return FormatTok;
1084 }
1085
1086private:
1087 FormatToken FormatTok;
1088 bool GreaterStashed;
1089 Lexer &Lex;
1090 SourceManager &SourceMgr;
1091 IdentifierTable IdentTable;
1092
1093 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001094 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001095 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1096 Tok.getLength());
1097 }
1098};
1099
Daniel Jasperbac016b2012-12-03 18:12:45 +00001100class Formatter : public UnwrappedLineConsumer {
1101public:
1102 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1103 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001104 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001105 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001106 }
1107
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001108 virtual ~Formatter() {
1109 }
1110
Daniel Jasperbac016b2012-12-03 18:12:45 +00001111 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001112 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1113 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001114 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001115 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001116 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1117 E = UnwrappedLines.end();
1118 I != E; ++I)
Manuel Klimekd4397b92013-01-04 23:34:14 +00001119 PreviousEndOfLineColumn =
1120 formatUnwrappedLine(*I, PreviousEndOfLineColumn);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001121 return Replaces;
1122 }
1123
1124private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001125 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001126 UnwrappedLines.push_back(TheLine);
1127 }
1128
Manuel Klimekd4397b92013-01-04 23:34:14 +00001129 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1130 unsigned PreviousEndOfLineColumn) {
1131 if (TheLine.Tokens.empty())
1132 return 0; // FIXME: Find out how this can ever happen.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001133
1134 CharSourceRange LineRange =
1135 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1136 TheLine.Tokens.back().Tok.getLocation());
1137
1138 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1139 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1140 Ranges[i].getBegin()) ||
1141 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1142 LineRange.getBegin()))
1143 continue;
1144
Manuel Klimek6cf58142013-01-07 08:54:53 +00001145 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasper1f42f112013-01-04 18:52:56 +00001146 if (!Annotator.annotate())
Manuel Klimekd4397b92013-01-04 23:34:14 +00001147 break;
1148 UnwrappedLineFormatter Formatter(
1149 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
1150 Annotator.getAnnotations(), Replaces, StructuralError);
1151 return Formatter.format();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001152 }
Manuel Klimekd4397b92013-01-04 23:34:14 +00001153 // If we did not reformat this unwrapped line, the column at the end of the
1154 // last token is unchanged - thus, we can calculate the end of the last
1155 // token, and return the result.
1156 const FormatToken &Token = TheLine.Tokens.back();
1157 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) +
1158 Lex.MeasureTokenLength(Token.Tok.getLocation(), SourceMgr,
1159 Lex.getLangOpts()) -
1160 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001161 }
1162
1163 FormatStyle Style;
1164 Lexer &Lex;
1165 SourceManager &SourceMgr;
1166 tooling::Replacements Replaces;
1167 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001168 std::vector<UnwrappedLine> UnwrappedLines;
1169 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001170};
1171
1172tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1173 SourceManager &SourceMgr,
1174 std::vector<CharSourceRange> Ranges) {
1175 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1176 return formatter.format();
1177}
1178
1179} // namespace format
1180} // namespace clang