blob: effe0bc2482106e5b0148a90b2474c9562c63050 [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 Jaspera4974cf2012-12-24 16:43:00 +0000102 Parameters.PenaltyLevelDecrease = 10;
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) +
Daniel Jasperd7610b82012-12-24 16:51:15 +0000134 Line.Tokens[i].Tok.getLength();
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.
137 if (Columns > Style.ColumnLimit ||
138 (Annotations[i].MustBreakBefore &&
139 Annotations[i].Type != TokenAnnotation::TT_CtorInitializerColon)) {
140 FitsOnALine = false;
141 break;
142 }
143 }
144
Daniel Jasperbac016b2012-12-03 18:12:45 +0000145 // Start iterating at 1 as we have correctly formatted of Token #0 above.
146 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000147 if (FitsOnALine) {
148 addTokenToState(false, false, State);
149 } else {
150 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
151 unsigned Break = calcPenalty(State, true, NoBreak);
152 addTokenToState(Break < NoBreak, false, State);
153 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000154 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000155 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000156 }
157
158private:
159 /// \brief The current state when indenting a unwrapped line.
160 ///
161 /// As the indenting tries different combinations this is copied by value.
162 struct IndentState {
163 /// \brief The number of used columns in the current line.
164 unsigned Column;
165
166 /// \brief The number of tokens already consumed.
167 unsigned ConsumedTokens;
168
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000169 /// \brief The parenthesis level of the first token on the current line.
170 unsigned StartOfLineLevel;
171
Daniel Jasperbac016b2012-12-03 18:12:45 +0000172 /// \brief The position to which a specific parenthesis level needs to be
173 /// indented.
174 std::vector<unsigned> Indent;
175
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000176 /// \brief The position of the last space on each level.
177 ///
178 /// Used e.g. to break like:
179 /// functionCall(Parameter, otherCall(
180 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000181 std::vector<unsigned> LastSpace;
182
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000183 /// \brief The position the first "<<" operator encountered on each level.
184 ///
185 /// Used to align "<<" operators. 0 if no such operator has been encountered
186 /// on a level.
187 std::vector<unsigned> FirstLessLess;
188
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000189 /// \brief The column of the first variable in a for-loop declaration.
190 ///
191 /// Used to align the second variable if necessary.
192 unsigned ForLoopVariablePos;
193
194 /// \brief \c true if this line contains a continued for-loop section.
195 bool LineContainsContinuedForLoopSection;
196
Daniel Jasperbac016b2012-12-03 18:12:45 +0000197 /// \brief Comparison operator to be able to used \c IndentState in \c map.
198 bool operator<(const IndentState &Other) const {
199 if (Other.ConsumedTokens != ConsumedTokens)
200 return Other.ConsumedTokens > ConsumedTokens;
201 if (Other.Column != Column)
202 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000203 if (Other.StartOfLineLevel != StartOfLineLevel)
204 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000205 if (Other.Indent.size() != Indent.size())
206 return Other.Indent.size() > Indent.size();
207 for (int i = 0, e = Indent.size(); i != e; ++i) {
208 if (Other.Indent[i] != Indent[i])
209 return Other.Indent[i] > Indent[i];
210 }
211 if (Other.LastSpace.size() != LastSpace.size())
212 return Other.LastSpace.size() > LastSpace.size();
213 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
214 if (Other.LastSpace[i] != LastSpace[i])
215 return Other.LastSpace[i] > LastSpace[i];
216 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000217 if (Other.FirstLessLess.size() != FirstLessLess.size())
218 return Other.FirstLessLess.size() > FirstLessLess.size();
219 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
220 if (Other.FirstLessLess[i] != FirstLessLess[i])
221 return Other.FirstLessLess[i] > FirstLessLess[i];
222 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000223 if (Other.ForLoopVariablePos != ForLoopVariablePos)
224 return Other.ForLoopVariablePos < ForLoopVariablePos;
225 if (Other.LineContainsContinuedForLoopSection !=
226 LineContainsContinuedForLoopSection)
227 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000228 return false;
229 }
230 };
231
Daniel Jasper20409152012-12-04 14:54:30 +0000232 /// \brief Appends the next token to \p State and updates information
233 /// necessary for indentation.
234 ///
235 /// Puts the token on the current line if \p Newline is \c true and adds a
236 /// line break and necessary indentation otherwise.
237 ///
238 /// If \p DryRun is \c false, also creates and stores the required
239 /// \c Replacement.
240 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000241 unsigned Index = State.ConsumedTokens;
242 const FormatToken &Current = Line.Tokens[Index];
243 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000244 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000245
246 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000247 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000248 if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000249 Previous.Tok.is(tok::string_literal)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000250 State.Column = State.Column - Previous.Tok.getLength();
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000251 } else if (Current.Tok.is(tok::lessless) &&
252 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000253 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000254 } else if (ParenLevel != 0 &&
255 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
256 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000257 // Indent and extra 4 spaces after '=' as it continues an expression.
258 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000259 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasperd7610b82012-12-24 16:51:15 +0000260 } else if (
261 Line.Tokens[0].Tok.is(tok::kw_for) && Previous.Tok.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000262 State.Column = State.ForLoopVariablePos;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000263 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
264 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000265 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000266 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000267 }
268
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000269 State.StartOfLineLevel = ParenLevel + 1;
270
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000271 if (Line.Tokens[0].Tok.is(tok::kw_for))
272 State.LineContainsContinuedForLoopSection =
273 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000274
Manuel Klimek060143e2013-01-02 18:33:23 +0000275 if (!DryRun) {
276 if (!Line.InPPDirective)
277 replaceWhitespace(Current, 1, State.Column);
278 else
279 replacePPWhitespace(Current, 1, State.Column, WhitespaceStartColumn);
280 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000281
Daniel Jaspera88bb452012-12-04 10:50:12 +0000282 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000283 if (Current.Tok.is(tok::colon) &&
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000284 Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr &&
285 Annotations[0].Type != TokenAnnotation::TT_ObjCMethodSpecifier)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000286 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000287 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000288 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
289 State.ForLoopVariablePos = State.Column - Previous.Tok.getLength();
290
Daniel Jasperbac016b2012-12-03 18:12:45 +0000291 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
292 if (Annotations[Index].Type == TokenAnnotation::TT_LineComment)
293 Spaces = 2;
Daniel Jasper20409152012-12-04 14:54:30 +0000294
Daniel Jasperbac016b2012-12-03 18:12:45 +0000295 if (!DryRun)
296 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000297
Daniel Jaspercf225b62012-12-24 13:43:52 +0000298 // FIXME: Look into using this alignment at other ParenLevels.
299 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
300 Previous.Tok.is(tok::kw_return)))
301 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper20409152012-12-04 14:54:30 +0000302 if (Previous.Tok.is(tok::l_paren) ||
303 Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000304 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000305
Daniel Jasperbac016b2012-12-03 18:12:45 +0000306 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000307 State.Column += Spaces;
Daniel Jaspera88bb452012-12-04 10:50:12 +0000308 if (Spaces > 0 && ParenLevel != 0)
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000309 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000310 }
Daniel Jasper20409152012-12-04 14:54:30 +0000311 moveStateToNextToken(State);
312 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000313
Daniel Jasper20409152012-12-04 14:54:30 +0000314 /// \brief Mark the next token as consumed in \p State and modify its stacks
315 /// accordingly.
316 void moveStateToNextToken(IndentState &State) {
317 unsigned Index = State.ConsumedTokens;
318 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000319 unsigned ParenLevel = State.Indent.size() - 1;
320
321 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
322 State.FirstLessLess[ParenLevel] = State.Column;
323
324 State.Column += Current.Tok.getLength();
Daniel Jasper20409152012-12-04 14:54:30 +0000325
Daniel Jaspercf225b62012-12-24 13:43:52 +0000326 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000327 // prepare for the following tokens.
328 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000329 Current.Tok.is(tok::l_brace) ||
Daniel Jasper20409152012-12-04 14:54:30 +0000330 Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) {
331 State.Indent.push_back(4 + State.LastSpace.back());
332 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000333 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000334 }
335
Daniel Jaspercf225b62012-12-24 13:43:52 +0000336 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000337 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000338 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000339 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jaspera88bb452012-12-04 10:50:12 +0000340 Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341 State.Indent.pop_back();
342 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000343 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000344 }
345
346 ++State.ConsumedTokens;
347 }
348
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000349 /// \brief Calculate the panelty for splitting after the token at \p Index.
350 unsigned splitPenalty(unsigned Index) {
351 assert(Index < Line.Tokens.size() &&
352 "Tried to calculate penalty for splitting after the last token");
353 const FormatToken &Left = Line.Tokens[Index];
354 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000355
356 // In for-loops, prefer breaking at ',' and ';'.
357 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
358 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
359 return 20;
360
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000361 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
362 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000363 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000364 if (Left.Tok.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000365 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000366
Daniel Jaspercf225b62012-12-24 13:43:52 +0000367 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000368 if (Level != prec::Unknown)
369 return Level;
370
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000371 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000372 return 50;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000373
Daniel Jasperbac016b2012-12-03 18:12:45 +0000374 return 3;
375 }
376
377 /// \brief Calculate the number of lines needed to format the remaining part
378 /// of the unwrapped line.
379 ///
380 /// Assumes the formatting so far has led to
381 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
382 /// added after the previous token.
383 ///
384 /// \param StopAt is used for optimization. If we can determine that we'll
385 /// definitely need at least \p StopAt additional lines, we already know of a
386 /// better solution.
387 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
388 // We are at the end of the unwrapped line, so we don't need any more lines.
389 if (State.ConsumedTokens >= Line.Tokens.size())
390 return 0;
391
392 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
393 return UINT_MAX;
394 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
395 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000396 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
397 State.LineContainsContinuedForLoopSection)
398 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399
Daniel Jasper33182dd2012-12-05 14:57:28 +0000400 unsigned CurrentPenalty = 0;
401 if (NewLine) {
402 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperd7610b82012-12-24 16:51:15 +0000403 splitPenalty(State.ConsumedTokens - 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000404 } else {
405 if (State.Indent.size() < State.StartOfLineLevel)
406 CurrentPenalty += Parameters.PenaltyLevelDecrease *
407 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000408 }
409
Daniel Jasper20409152012-12-04 14:54:30 +0000410 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000411
412 // Exceeding column limit is bad.
Manuel Klimek060143e2013-01-02 18:33:23 +0000413 if (State.Column > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000414 return UINT_MAX;
415
Daniel Jasperbac016b2012-12-03 18:12:45 +0000416 if (StopAt <= CurrentPenalty)
417 return UINT_MAX;
418 StopAt -= CurrentPenalty;
419
Daniel Jasperbac016b2012-12-03 18:12:45 +0000420 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000421 if (I != Memory.end()) {
422 // If this state has already been examined, we can safely return the
423 // previous result if we
424 // - have not hit the optimatization (and thus returned UINT_MAX) OR
425 // - are now computing for a smaller or equal StopAt.
426 unsigned SavedResult = I->second.first;
427 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000428 if (SavedResult != UINT_MAX)
429 return SavedResult + CurrentPenalty;
430 else if (StopAt <= SavedStopAt)
431 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000432 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000433
434 unsigned NoBreak = calcPenalty(State, false, StopAt);
435 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
436 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000437
438 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
439 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000440 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000441
442 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000443 }
444
445 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
446 /// each \c FormatToken.
447 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
448 unsigned Spaces) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000449 Replaces.insert(tooling::Replacement(
450 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
451 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
452 }
453
454 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
455 /// backslashes to escape newlines inside a preprocessor directive.
456 ///
457 /// This function and \c replaceWhitespace have the same behavior if
458 /// \c Newlines == 0.
459 void replacePPWhitespace(const FormatToken &Tok, unsigned NewLines,
460 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000461 std::string NewLineText;
Manuel Klimek060143e2013-01-02 18:33:23 +0000462 if (NewLines > 0) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000463 unsigned Offset =
Manuel Klimek060143e2013-01-02 18:33:23 +0000464 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Manuel Klimeka080a182013-01-02 16:30:12 +0000465 for (unsigned i = 0; i < NewLines; ++i) {
466 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
467 NewLineText += "\\\n";
468 Offset = 0;
469 }
470 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000471 Replaces.insert(tooling::Replacement(
472 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
Manuel Klimeka080a182013-01-02 16:30:12 +0000473 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000474 }
475
476 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000477 /// of the \c UnwrappedLine if there was no structural parsing error.
478 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000479 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000480 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000481 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
482 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
483
484 unsigned Newlines =
485 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
486 unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart);
487 if (Newlines == 0 && Offset != 0)
488 Newlines = 1;
489 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000490 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
491 Token.Tok.is(tok::kw_private)) &&
492 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000493 Indent += Style.AccessModifierOffset;
Manuel Klimek060143e2013-01-02 18:33:23 +0000494 if (!Line.InPPDirective || Token.HasUnescapedNewline)
495 replaceWhitespace(Token, Newlines, Indent);
496 else
Manuel Klimekd4397b92013-01-04 23:34:14 +0000497 replacePPWhitespace(Token, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000498 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000499 }
500
501 FormatStyle Style;
502 SourceManager &SourceMgr;
503 const UnwrappedLine &Line;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000504 const unsigned PreviousEndOfLineColumn;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000505 const std::vector<TokenAnnotation> &Annotations;
506 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000507 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000508
Daniel Jasper33182dd2012-12-05 14:57:28 +0000509 // A map from an indent state to a pair (Result, Used-StopAt).
510 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
511 StateMap Memory;
512
Daniel Jasperbac016b2012-12-03 18:12:45 +0000513 OptimizationParameters Parameters;
514};
515
516/// \brief Determines extra information about the tokens comprising an
517/// \c UnwrappedLine.
518class TokenAnnotator {
519public:
520 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
521 SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000522 : Line(Line), Style(Style), SourceMgr(SourceMgr) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000523 }
524
525 /// \brief A parser that gathers additional information about tokens.
526 ///
527 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
528 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
529 /// into template parameter lists.
530 class AnnotatingParser {
531 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000532 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000533 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000534 : Tokens(Tokens), Annotations(Annotations), Index(0) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 }
536
Daniel Jasper20409152012-12-04 14:54:30 +0000537 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000538 while (Index < Tokens.size()) {
539 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jaspera88bb452012-12-04 10:50:12 +0000540 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000541 next();
542 return true;
543 }
544 if (Tokens[Index].Tok.is(tok::r_paren) ||
Daniel Jasper1f42f112013-01-04 18:52:56 +0000545 Tokens[Index].Tok.is(tok::r_square) ||
546 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000547 return false;
548 if (Tokens[Index].Tok.is(tok::pipepipe) ||
549 Tokens[Index].Tok.is(tok::ampamp) ||
550 Tokens[Index].Tok.is(tok::question) ||
551 Tokens[Index].Tok.is(tok::colon))
552 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000553 if (!consumeToken())
554 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000555 }
556 return false;
557 }
558
Daniel Jasper20409152012-12-04 14:54:30 +0000559 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560 while (Index < Tokens.size()) {
561 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000562 next();
563 return true;
564 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000565 if (Tokens[Index].Tok.is(tok::r_square) ||
566 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000567 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000568 if (!consumeToken())
569 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000570 }
571 return false;
572 }
573
Daniel Jasper20409152012-12-04 14:54:30 +0000574 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000575 while (Index < Tokens.size()) {
576 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000577 next();
578 return true;
579 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000580 if (Tokens[Index].Tok.is(tok::r_paren) ||
581 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000582 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000583 if (!consumeToken())
584 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000585 }
586 return false;
587 }
588
Daniel Jasper20409152012-12-04 14:54:30 +0000589 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000590 while (Index < Tokens.size()) {
591 if (Tokens[Index].Tok.is(tok::colon)) {
592 Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr;
593 next();
594 return true;
595 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000596 if (!consumeToken())
597 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000598 }
599 return false;
600 }
601
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000602 bool parseTemplateDeclaration() {
603 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
604 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
605 next();
606 if (!parseAngle())
607 return false;
608 Annotations[Index - 1].ClosesTemplateDeclaration = true;
609 parseLine();
610 return true;
611 }
612 return false;
613 }
614
Daniel Jasper1f42f112013-01-04 18:52:56 +0000615 bool consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000616 unsigned CurrentIndex = Index;
617 next();
618 switch (Tokens[CurrentIndex].Tok.getKind()) {
619 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000620 if (!parseParens())
621 return false;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000622 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
623 Annotations[Index].Type = TokenAnnotation::TT_CtorInitializerColon;
624 next();
625 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000626 break;
627 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000628 if (!parseSquare())
629 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000630 break;
631 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000632 if (parseAngle())
Daniel Jasperbac016b2012-12-03 18:12:45 +0000633 Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener;
634 else {
635 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
636 Index = CurrentIndex + 1;
637 }
638 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000639 case tok::r_paren:
640 case tok::r_square:
641 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000642 case tok::greater:
643 Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator;
644 break;
645 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000646 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000647 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000648 next();
649 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
650 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
651 next();
652 }
653 } else {
654 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
655 Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator;
656 next();
657 }
658 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000659 break;
660 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000661 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000662 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000663 case tok::kw_template:
664 parseTemplateDeclaration();
665 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000666 default:
667 break;
668 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000669 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000670 }
671
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000672 void parseIncludeDirective() {
673 while (Index < Tokens.size()) {
674 if (Tokens[Index].Tok.is(tok::slash))
675 Annotations[Index].Type = TokenAnnotation::TT_DirectorySeparator;
676 else if (Tokens[Index].Tok.is(tok::less))
677 Annotations[Index].Type = TokenAnnotation::TT_TemplateOpener;
678 else if (Tokens[Index].Tok.is(tok::greater))
679 Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser;
680 next();
681 }
682 }
683
684 void parsePreprocessorDirective() {
685 next();
686 if (Index >= Tokens.size())
687 return;
Manuel Klimeka080a182013-01-02 16:30:12 +0000688 // It is the responsibility of the UnwrappedLineParser to make sure
689 // this sequence is not produced inside an unwrapped line.
690 assert(Tokens[Index].Tok.getIdentifierInfo() != NULL);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000691 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
692 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000693 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000694 parseIncludeDirective();
695 break;
696 default:
697 break;
698 }
699 }
700
Daniel Jasper1f42f112013-01-04 18:52:56 +0000701 bool parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000702 if (Tokens[Index].Tok.is(tok::hash)) {
703 parsePreprocessorDirective();
Daniel Jasper1f42f112013-01-04 18:52:56 +0000704 return true;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000705 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000706 while (Index < Tokens.size()) {
Daniel Jasper1f42f112013-01-04 18:52:56 +0000707 if (!consumeToken())
708 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000709 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000710 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000711 }
712
713 void next() {
714 ++Index;
715 }
716
717 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000718 const SmallVector<FormatToken, 16> &Tokens;
719 std::vector<TokenAnnotation> &Annotations;
720 unsigned Index;
721 };
722
Daniel Jasper1f42f112013-01-04 18:52:56 +0000723 bool annotate() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000724 Annotations.clear();
725 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
726 Annotations.push_back(TokenAnnotation());
727 }
728
Manuel Klimek0be4b362012-12-03 20:55:42 +0000729 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasper1f42f112013-01-04 18:52:56 +0000730 if (!Parser.parseLine())
731 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732
733 determineTokenTypes();
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000734 bool IsObjCMethodDecl =
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000735 (Line.Tokens.size() > 0 &&
736 (Annotations[0].Type == TokenAnnotation::TT_ObjCMethodSpecifier));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000737 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
738 TokenAnnotation &Annotation = Annotations[i];
739
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000740 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741
Daniel Jasper1321eb52012-12-18 21:05:13 +0000742 if (Annotation.Type == TokenAnnotation::TT_CtorInitializerColon) {
743 Annotation.MustBreakBefore = true;
744 Annotation.SpaceRequiredBefore = true;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000745 } else if (Annotation.Type == TokenAnnotation::TT_OverloadedOperator) {
746 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-12-24 16:51:15 +0000747 Line.Tokens[i].Tok.is(tok::identifier) ||
748 Line.Tokens[i].Tok.is(tok::kw_new) ||
749 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000750 } else if (
751 Annotations[i - 1].Type == TokenAnnotation::TT_OverloadedOperator) {
752 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000753 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
754 (i != e - 1) && Line.Tokens[i + 1].Tok.is(tok::colon) &&
755 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000756 Annotation.CanBreakBefore = true;
757 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000758 } else if (IsObjCMethodDecl && Line.Tokens[i].Tok.is(tok::identifier) &&
759 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
760 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000761 // Don't break this identifier as ':' or identifier
762 // before it will break.
763 Annotation.CanBreakBefore = false;
764 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000765 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000766 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000767 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000768 Annotation.MustBreakBefore = true;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000769 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasperdfbb3192012-12-05 16:24:48 +0000770 Annotation.SpaceRequiredBefore =
Daniel Jasperd7610b82012-12-24 16:51:15 +0000771 Line.Tokens[0].Tok.isNot(tok::kw_case) && !IsObjCMethodDecl &&
772 (i != e - 1);
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000773 // Don't break at ':' if identifier before it can beak.
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000774 if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::identifier) &&
775 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000776 Annotation.CanBreakBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000777 } else if (
778 Annotations[i - 1].Type == TokenAnnotation::TT_ObjCMethodSpecifier) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000779 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000780 } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000781 Annotation.SpaceRequiredBefore = false;
782 } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) {
783 Annotation.SpaceRequiredBefore =
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000784 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
785 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000786 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
787 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000788 if (Annotation.Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasper20409152012-12-04 14:54:30 +0000789 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser)
Daniel Jaspera88bb452012-12-04 10:50:12 +0000790 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000791 else
792 Annotation.SpaceRequiredBefore = false;
793 } else if (
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000794 Annotation.Type == TokenAnnotation::TT_DirectorySeparator ||
795 Annotations[i - 1].Type == TokenAnnotation::TT_DirectorySeparator) {
796 Annotation.SpaceRequiredBefore = false;
797 } else if (
Daniel Jasperbac016b2012-12-03 18:12:45 +0000798 Annotation.Type == TokenAnnotation::TT_BinaryOperator ||
799 Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) {
800 Annotation.SpaceRequiredBefore = true;
801 } else if (
Daniel Jaspera88bb452012-12-04 10:50:12 +0000802 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser &&
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 Line.Tokens[i].Tok.is(tok::l_paren)) {
804 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8822d3a2012-12-04 13:02:32 +0000805 } else if (Line.Tokens[i].Tok.is(tok::less) &&
806 Line.Tokens[0].Tok.is(tok::hash)) {
807 Annotation.SpaceRequiredBefore = true;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000808 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
809 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000810 // Don't space between ')' and <id>
811 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000812 } else if (IsObjCMethodDecl && Line.Tokens[i - 1].Tok.is(tok::colon) &&
813 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000814 // Don't space between ':' and '('
815 Annotation.SpaceRequiredBefore = false;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000816 } else if (Annotation.Type == TokenAnnotation::TT_TrailingUnaryOperator) {
817 Annotation.SpaceRequiredBefore = false;
818 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000819 Annotation.SpaceRequiredBefore =
820 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
821 }
822
823 if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment ||
824 (Line.Tokens[i].Tok.is(tok::string_literal) &&
825 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
826 Annotation.MustBreakBefore = true;
827 }
828
829 if (Annotation.MustBreakBefore)
830 Annotation.CanBreakBefore = true;
831 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000832 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000833 }
834
835 const std::vector<TokenAnnotation> &getAnnotations() {
836 return Annotations;
837 }
838
839private:
840 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000841 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000842 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
843 TokenAnnotation &Annotation = Annotations[i];
844 const FormatToken &Tok = Line.Tokens[i];
845
Daniel Jaspercf225b62012-12-24 13:43:52 +0000846 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber00d5a042012-12-23 01:07:46 +0000847 IsRHS = true;
848 else if (Tok.Tok.is(tok::kw_return))
849 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000850
Daniel Jasper675d2e32012-12-21 10:20:02 +0000851 if (Annotation.Type != TokenAnnotation::TT_Unknown)
852 continue;
853
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000854 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000855 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000856 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
857 Annotation.Type = determinePlusMinusUsage(i);
858 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
859 Annotation.Type = determineIncrementUsage(i);
860 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000861 Annotation.Type = TokenAnnotation::TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000862 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000863 Annotation.Type = TokenAnnotation::TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000864 } else if (Tok.Tok.is(tok::comment)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000865 StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
866 Tok.Tok.getLength());
867 if (Data.startswith("//"))
868 Annotation.Type = TokenAnnotation::TT_LineComment;
869 else
870 Annotation.Type = TokenAnnotation::TT_BlockComment;
871 }
872 }
873 }
874
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000876 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000877 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000878 }
879
Daniel Jasperd7610b82012-12-24 16:51:15 +0000880 TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperba3d3072013-01-02 17:21:36 +0000881 if (Index == 0)
882 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000883 if (Index == Annotations.size())
884 return TokenAnnotation::TT_Unknown;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000885 const FormatToken &PrevToken = Line.Tokens[Index - 1];
886 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000887
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000888 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
889 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
890 PrevToken.Tok.is(tok::colon) ||
Daniel Jasperbac016b2012-12-03 18:12:45 +0000891 Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
892 return TokenAnnotation::TT_UnaryOperator;
893
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000894 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000895 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
896 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
897 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
898 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000899 return TokenAnnotation::TT_BinaryOperator;
900
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000901 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
902 NextToken.Tok.is(tok::greater))
903 return TokenAnnotation::TT_PointerOrReference;
904
Daniel Jasper112fb272012-12-05 07:51:39 +0000905 // It is very unlikely that we are going to find a pointer or reference type
906 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000907 if (IsRHS)
Daniel Jasper112fb272012-12-05 07:51:39 +0000908 return TokenAnnotation::TT_BinaryOperator;
909
Daniel Jasperbac016b2012-12-03 18:12:45 +0000910 return TokenAnnotation::TT_PointerOrReference;
911 }
912
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000913 TokenAnnotation::TokenType determinePlusMinusUsage(unsigned Index) {
914 // At the start of the line, +/- specific ObjectiveC method declarations.
915 if (Index == 0)
916 return TokenAnnotation::TT_ObjCMethodSpecifier;
917
918 // Use heuristics to recognize unary operators.
919 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
920 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
921 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasper1f0754b2013-01-02 15:26:16 +0000922 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
923 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000924 return TokenAnnotation::TT_UnaryOperator;
925
926 // There can't be to consecutive binary operators.
927 if (Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator)
928 return TokenAnnotation::TT_UnaryOperator;
929
930 // Fall back to marking the token as binary operator.
931 return TokenAnnotation::TT_BinaryOperator;
932 }
933
934 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
935 TokenAnnotation::TokenType determineIncrementUsage(unsigned Index) {
936 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
937 return TokenAnnotation::TT_TrailingUnaryOperator;
938
939 return TokenAnnotation::TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000940 }
941
942 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000943 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
944 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000945 if (Left.is(tok::kw_template) && Right.is(tok::less))
946 return true;
947 if (Left.is(tok::arrow) || Right.is(tok::arrow))
948 return false;
949 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
950 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000951 if (Left.is(tok::at) && Right.is(tok::identifier))
952 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000953 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
954 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000955 if (Right.is(tok::amp) || Right.is(tok::star))
956 return Left.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000957 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
958 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000959 if (Left.is(tok::amp) || Left.is(tok::star))
960 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
961 if (Right.is(tok::star) && Left.is(tok::l_paren))
962 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000963 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
964 Right.is(tok::r_square))
965 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000966 if (Left.is(tok::coloncolon) ||
967 (Right.is(tok::coloncolon) &&
968 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000969 return false;
970 if (Left.is(tok::period) || Right.is(tok::period))
971 return false;
972 if (Left.is(tok::colon) || Right.is(tok::colon))
973 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000974 if (Left.is(tok::l_paren))
975 return false;
976 if (Left.is(tok::hash))
977 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000979 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000980 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
981 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasperba3d3072013-01-02 17:21:36 +0000982 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000983 }
984 return true;
985 }
986
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000987 bool canBreakBefore(unsigned i) {
Daniel Jasper5eda31e2013-01-02 18:30:06 +0000988 if (Annotations[i - 1].ClosesTemplateDeclaration)
989 return true;
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000990 if (Annotations[i - 1].Type == TokenAnnotation::TT_PointerOrReference ||
Daniel Jasper5eda31e2013-01-02 18:30:06 +0000991 Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser ||
Daniel Jasper4dc41de2013-01-02 08:44:14 +0000992 Annotations[i].Type == TokenAnnotation::TT_ConditionalExpr) {
993 return false;
994 }
995 const FormatToken &Left = Line.Tokens[i - 1];
996 const FormatToken &Right = Line.Tokens[i];
Daniel Jasper05b1ac82012-12-17 11:29:41 +0000997 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
998 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000999 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +00001000 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001001 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
1002 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
1003 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
1004 Left.Tok.is(tok::l_brace) ||
1005 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001006 }
1007
1008 const UnwrappedLine &Line;
1009 FormatStyle Style;
1010 SourceManager &SourceMgr;
1011 std::vector<TokenAnnotation> Annotations;
1012};
1013
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001014class LexerBasedFormatTokenSource : public FormatTokenSource {
1015public:
1016 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001017 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001018 IdentTable(Lex.getLangOpts()) {
1019 Lex.SetKeepWhitespaceMode(true);
1020 }
1021
1022 virtual FormatToken getNextToken() {
1023 if (GreaterStashed) {
1024 FormatTok.NewlinesBefore = 0;
1025 FormatTok.WhiteSpaceStart =
1026 FormatTok.Tok.getLocation().getLocWithOffset(1);
1027 FormatTok.WhiteSpaceLength = 0;
1028 GreaterStashed = false;
1029 return FormatTok;
1030 }
1031
1032 FormatTok = FormatToken();
1033 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001034 StringRef Text = tokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001035 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
1036
1037 // Consume and record whitespace until we find a significant token.
1038 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001039 FormatTok.NewlinesBefore += Text.count('\n');
1040 FormatTok.HasUnescapedNewline =
1041 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001042 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1043
1044 if (FormatTok.Tok.is(tok::eof))
1045 return FormatTok;
1046 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001047 Text = tokenText(FormatTok.Tok);
1048 }
1049 // In case the token starts with escaped newlines, we want to
1050 // take them into account as whitespace - this pattern is quite frequent
1051 // in macro definitions.
1052 // FIXME: What do we want to do with other escaped spaces, and escaped
1053 // spaces or newlines in the middle of tokens?
1054 // FIXME: Add a more explicit test.
1055 unsigned i = 0;
1056 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i+1] == '\n') {
1057 FormatTok.WhiteSpaceLength += 2;
1058 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001059 }
1060
1061 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001062 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001063 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001064 FormatTok.Tok.setKind(Info.getTokenID());
1065 }
1066
1067 if (FormatTok.Tok.is(tok::greatergreater)) {
1068 FormatTok.Tok.setKind(tok::greater);
1069 GreaterStashed = true;
1070 }
1071
1072 return FormatTok;
1073 }
1074
1075private:
1076 FormatToken FormatTok;
1077 bool GreaterStashed;
1078 Lexer &Lex;
1079 SourceManager &SourceMgr;
1080 IdentifierTable IdentTable;
1081
1082 /// Returns the text of \c FormatTok.
1083 StringRef tokenText(Token &Tok) {
1084 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1085 Tok.getLength());
1086 }
1087};
1088
Daniel Jasperbac016b2012-12-03 18:12:45 +00001089class Formatter : public UnwrappedLineConsumer {
1090public:
1091 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1092 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001093 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001094 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001095 }
1096
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001097 virtual ~Formatter() {
1098 }
1099
Daniel Jasperbac016b2012-12-03 18:12:45 +00001100 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001101 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1102 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001103 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001104 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001105 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1106 E = UnwrappedLines.end();
1107 I != E; ++I)
Manuel Klimekd4397b92013-01-04 23:34:14 +00001108 PreviousEndOfLineColumn =
1109 formatUnwrappedLine(*I, PreviousEndOfLineColumn);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001110 return Replaces;
1111 }
1112
1113private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001114 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001115 UnwrappedLines.push_back(TheLine);
1116 }
1117
Manuel Klimekd4397b92013-01-04 23:34:14 +00001118 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1119 unsigned PreviousEndOfLineColumn) {
1120 if (TheLine.Tokens.empty())
1121 return 0; // FIXME: Find out how this can ever happen.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001122
1123 CharSourceRange LineRange =
1124 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1125 TheLine.Tokens.back().Tok.getLocation());
1126
1127 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1128 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1129 Ranges[i].getBegin()) ||
1130 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1131 LineRange.getBegin()))
1132 continue;
1133
1134 TokenAnnotator Annotator(TheLine, Style, SourceMgr);
Daniel Jasper1f42f112013-01-04 18:52:56 +00001135 if (!Annotator.annotate())
Manuel Klimekd4397b92013-01-04 23:34:14 +00001136 break;
1137 UnwrappedLineFormatter Formatter(
1138 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
1139 Annotator.getAnnotations(), Replaces, StructuralError);
1140 return Formatter.format();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001141 }
Manuel Klimekd4397b92013-01-04 23:34:14 +00001142 // If we did not reformat this unwrapped line, the column at the end of the
1143 // last token is unchanged - thus, we can calculate the end of the last
1144 // token, and return the result.
1145 const FormatToken &Token = TheLine.Tokens.back();
1146 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) +
1147 Lex.MeasureTokenLength(Token.Tok.getLocation(), SourceMgr,
1148 Lex.getLangOpts()) -
1149 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150 }
1151
1152 FormatStyle Style;
1153 Lexer &Lex;
1154 SourceManager &SourceMgr;
1155 tooling::Replacements Replaces;
1156 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001157 std::vector<UnwrappedLine> UnwrappedLines;
1158 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001159};
1160
1161tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1162 SourceManager &SourceMgr,
1163 std::vector<CharSourceRange> Ranges) {
1164 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1165 return formatter.format();
1166}
1167
1168} // namespace format
1169} // namespace clang