blob: 7a6b6e2081b836ae4c43258c449307ad879bc2ef [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
Daniel Jasper71607512013-01-07 10:48:50 +000029enum TokenType {
30 TT_Unknown,
31 TT_TemplateOpener,
32 TT_TemplateCloser,
33 TT_BinaryOperator,
34 TT_UnaryOperator,
35 TT_TrailingUnaryOperator,
36 TT_OverloadedOperator,
37 TT_PointerOrReference,
38 TT_ConditionalExpr,
39 TT_CtorInitializerColon,
40 TT_LineComment,
41 TT_BlockComment,
42 TT_DirectorySeparator,
43 TT_PureVirtualSpecifier,
44 TT_ObjCMethodSpecifier
45};
46
47enum LineType {
48 LT_Invalid,
49 LT_Other,
50 LT_PreprocessorDirective,
51 LT_VirtualFunctionDecl,
52 LT_ObjCMethodDecl
53};
54
Daniel Jasperbac016b2012-12-03 18:12:45 +000055// FIXME: Move somewhere sane.
56struct TokenAnnotation {
Daniel Jasperbac016b2012-12-03 18:12:45 +000057 TokenType Type;
58
Daniel Jasperbac016b2012-12-03 18:12:45 +000059 bool SpaceRequiredBefore;
60 bool CanBreakBefore;
61 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000062
63 bool ClosesTemplateDeclaration;
Daniel Jasperbac016b2012-12-03 18:12:45 +000064};
65
Daniel Jaspercf225b62012-12-24 13:43:52 +000066static prec::Level getPrecedence(const FormatToken &Tok) {
67 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
68}
69
Daniel Jasperbac016b2012-12-03 18:12:45 +000070using llvm::MutableArrayRef;
71
72FormatStyle getLLVMStyle() {
73 FormatStyle LLVMStyle;
74 LLVMStyle.ColumnLimit = 80;
75 LLVMStyle.MaxEmptyLinesToKeep = 1;
76 LLVMStyle.PointerAndReferenceBindToType = false;
77 LLVMStyle.AccessModifierOffset = -2;
78 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +000079 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000080 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +000081 return LLVMStyle;
82}
83
84FormatStyle getGoogleStyle() {
85 FormatStyle GoogleStyle;
86 GoogleStyle.ColumnLimit = 80;
87 GoogleStyle.MaxEmptyLinesToKeep = 1;
88 GoogleStyle.PointerAndReferenceBindToType = true;
89 GoogleStyle.AccessModifierOffset = -1;
90 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +000091 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +000092 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +000093 return GoogleStyle;
94}
95
96struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +000097 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +000098 unsigned PenaltyLevelDecrease;
Daniel Jasperbac016b2012-12-03 18:12:45 +000099};
100
101class UnwrappedLineFormatter {
102public:
103 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
104 const UnwrappedLine &Line,
Manuel Klimekd4397b92013-01-04 23:34:14 +0000105 unsigned PreviousEndOfLineColumn,
Daniel Jasper71607512013-01-07 10:48:50 +0000106 LineType CurrentLineType,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000107 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000108 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000109 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekd4397b92013-01-04 23:34:14 +0000110 PreviousEndOfLineColumn(PreviousEndOfLineColumn),
Daniel Jasper71607512013-01-07 10:48:50 +0000111 CurrentLineType(CurrentLineType), Annotations(Annotations),
112 Replaces(Replaces), StructuralError(StructuralError) {
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000113 Parameters.PenaltyIndentLevel = 15;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000114 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000115 }
116
Manuel Klimekd4397b92013-01-04 23:34:14 +0000117 /// \brief Formats an \c UnwrappedLine.
118 ///
119 /// \returns The column after the last token in the last line of the
120 /// \c UnwrappedLine.
121 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000122 // Format first token and initialize indent.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000123 unsigned Indent = formatFirstToken();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000124
125 // Initialize state dependent on indent.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000126 IndentState State;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000127 State.Column = Indent;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000128 State.ConsumedTokens = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000129 State.Indent.push_back(Indent + 4);
130 State.LastSpace.push_back(Indent);
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000131 State.FirstLessLess.push_back(0);
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000132 State.ForLoopVariablePos = 0;
133 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000134 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000135
136 // The first token has already been indented and thus consumed.
137 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000138
Daniel Jasper1321eb52012-12-18 21:05:13 +0000139 // Check whether the UnwrappedLine can be put onto a single line. If so,
140 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasper1f42f112013-01-04 18:52:56 +0000141 // need to analyze the entire solution space.
Daniel Jasper1321eb52012-12-18 21:05:13 +0000142 unsigned Columns = State.Column;
143 bool FitsOnALine = true;
144 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
145 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
Manuel Klimek95419382013-01-07 07:56:50 +0000146 Line.Tokens[i].TokenLength;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000147 // A special case for the colon of a constructor initializer as this only
148 // needs to be put on a new line if the line needs to be split.
Manuel Klimekd544c572013-01-07 09:24:17 +0000149 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper1321eb52012-12-18 21:05:13 +0000150 (Annotations[i].MustBreakBefore &&
Daniel Jasper71607512013-01-07 10:48:50 +0000151 Annotations[i].Type != TT_CtorInitializerColon)) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000152 FitsOnALine = false;
153 break;
154 }
155 }
156
Daniel Jasperbac016b2012-12-03 18:12:45 +0000157 // Start iterating at 1 as we have correctly formatted of Token #0 above.
158 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000159 if (FitsOnALine) {
160 addTokenToState(false, false, State);
161 } else {
162 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
163 unsigned Break = calcPenalty(State, true, NoBreak);
164 addTokenToState(Break < NoBreak, false, State);
165 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000166 }
Manuel Klimekd4397b92013-01-04 23:34:14 +0000167 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000168 }
169
170private:
171 /// \brief The current state when indenting a unwrapped line.
172 ///
173 /// As the indenting tries different combinations this is copied by value.
174 struct IndentState {
175 /// \brief The number of used columns in the current line.
176 unsigned Column;
177
178 /// \brief The number of tokens already consumed.
179 unsigned ConsumedTokens;
180
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000181 /// \brief The parenthesis level of the first token on the current line.
182 unsigned StartOfLineLevel;
183
Daniel Jasperbac016b2012-12-03 18:12:45 +0000184 /// \brief The position to which a specific parenthesis level needs to be
185 /// indented.
186 std::vector<unsigned> Indent;
187
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000188 /// \brief The position of the last space on each level.
189 ///
190 /// Used e.g. to break like:
191 /// functionCall(Parameter, otherCall(
192 /// OtherParameter));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000193 std::vector<unsigned> LastSpace;
194
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000195 /// \brief The position the first "<<" operator encountered on each level.
196 ///
197 /// Used to align "<<" operators. 0 if no such operator has been encountered
198 /// on a level.
199 std::vector<unsigned> FirstLessLess;
200
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000201 /// \brief The column of the first variable in a for-loop declaration.
202 ///
203 /// Used to align the second variable if necessary.
204 unsigned ForLoopVariablePos;
205
206 /// \brief \c true if this line contains a continued for-loop section.
207 bool LineContainsContinuedForLoopSection;
208
Daniel Jasperbac016b2012-12-03 18:12:45 +0000209 /// \brief Comparison operator to be able to used \c IndentState in \c map.
210 bool operator<(const IndentState &Other) const {
211 if (Other.ConsumedTokens != ConsumedTokens)
212 return Other.ConsumedTokens > ConsumedTokens;
213 if (Other.Column != Column)
214 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000215 if (Other.StartOfLineLevel != StartOfLineLevel)
216 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000217 if (Other.Indent.size() != Indent.size())
218 return Other.Indent.size() > Indent.size();
219 for (int i = 0, e = Indent.size(); i != e; ++i) {
220 if (Other.Indent[i] != Indent[i])
221 return Other.Indent[i] > Indent[i];
222 }
223 if (Other.LastSpace.size() != LastSpace.size())
224 return Other.LastSpace.size() > LastSpace.size();
225 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
226 if (Other.LastSpace[i] != LastSpace[i])
227 return Other.LastSpace[i] > LastSpace[i];
228 }
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000229 if (Other.FirstLessLess.size() != FirstLessLess.size())
230 return Other.FirstLessLess.size() > FirstLessLess.size();
231 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
232 if (Other.FirstLessLess[i] != FirstLessLess[i])
233 return Other.FirstLessLess[i] > FirstLessLess[i];
234 }
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000235 if (Other.ForLoopVariablePos != ForLoopVariablePos)
236 return Other.ForLoopVariablePos < ForLoopVariablePos;
237 if (Other.LineContainsContinuedForLoopSection !=
238 LineContainsContinuedForLoopSection)
239 return LineContainsContinuedForLoopSection;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000240 return false;
241 }
242 };
243
Daniel Jasper20409152012-12-04 14:54:30 +0000244 /// \brief Appends the next token to \p State and updates information
245 /// necessary for indentation.
246 ///
247 /// Puts the token on the current line if \p Newline is \c true and adds a
248 /// line break and necessary indentation otherwise.
249 ///
250 /// If \p DryRun is \c false, also creates and stores the required
251 /// \c Replacement.
252 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000253 unsigned Index = State.ConsumedTokens;
254 const FormatToken &Current = Line.Tokens[Index];
255 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper20409152012-12-04 14:54:30 +0000256 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000257
258 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000259 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000260 if (Previous.Tok.is(tok::l_brace)) {
261 // FIXME: This does not work with nested static initializers.
262 // Implement a better handling for static initializers and similar
263 // constructs.
264 State.Column = Line.Level * 2 + 2;
265 } else if (Current.Tok.is(tok::string_literal) &&
Daniel Jaspercd162382013-01-07 13:26:07 +0000266 Previous.Tok.is(tok::string_literal)) {
Manuel Klimek95419382013-01-07 07:56:50 +0000267 State.Column = State.Column - Previous.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000268 } else if (Current.Tok.is(tok::lessless) &&
269 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000270 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000271 } else if (ParenLevel != 0 &&
272 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
273 Current.Tok.is(tok::period))) {
Daniel Jasper20409152012-12-04 14:54:30 +0000274 // Indent and extra 4 spaces after '=' as it continues an expression.
275 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperbac016b2012-12-03 18:12:45 +0000276 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper71607512013-01-07 10:48:50 +0000277 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
278 Previous.Tok.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000279 State.Column = State.ForLoopVariablePos;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000280 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
281 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000282 } else {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000283 State.Column = State.Indent[ParenLevel];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000284 }
285
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000286 State.StartOfLineLevel = ParenLevel + 1;
287
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000288 if (Line.Tokens[0].Tok.is(tok::kw_for))
289 State.LineContainsContinuedForLoopSection =
290 Previous.Tok.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000291
Manuel Klimek060143e2013-01-02 18:33:23 +0000292 if (!DryRun) {
293 if (!Line.InPPDirective)
294 replaceWhitespace(Current, 1, State.Column);
295 else
296 replacePPWhitespace(Current, 1, State.Column, WhitespaceStartColumn);
297 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000298
Daniel Jaspera88bb452012-12-04 10:50:12 +0000299 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasper71607512013-01-07 10:48:50 +0000300 if (Current.Tok.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
301 Annotations[Index].Type != TT_ConditionalExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000302 State.Indent[ParenLevel] += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000303 } else {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000304 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
Manuel Klimek95419382013-01-07 07:56:50 +0000305 State.ForLoopVariablePos = State.Column - Previous.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000306
Daniel Jasperbac016b2012-12-03 18:12:45 +0000307 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
Daniel Jasper71607512013-01-07 10:48:50 +0000308 if (Annotations[Index].Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000309 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000310
Daniel Jasperbac016b2012-12-03 18:12:45 +0000311 if (!DryRun)
312 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper20409152012-12-04 14:54:30 +0000313
Daniel Jasper9cda8002013-01-07 13:08:40 +0000314 if (Line.Tokens[0].Tok.isNot(tok::kw_for) &&
315 (getPrecedence(Previous) == prec::Assignment ||
316 Previous.Tok.is(tok::kw_return)))
Daniel Jaspercf225b62012-12-24 13:43:52 +0000317 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper20409152012-12-04 14:54:30 +0000318 if (Previous.Tok.is(tok::l_paren) ||
Daniel Jasper71607512013-01-07 10:48:50 +0000319 Annotations[Index - 1].Type == TT_TemplateOpener)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000320 State.Indent[ParenLevel] = State.Column;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000321
Daniel Jasper9cda8002013-01-07 13:08:40 +0000322 // Top-level spaces that are not part of assignments are exempt as that
323 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000324 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000325 if (Spaces > 0 &&
326 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000327 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000328 }
Daniel Jasper20409152012-12-04 14:54:30 +0000329 moveStateToNextToken(State);
330 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000331
Daniel Jasper20409152012-12-04 14:54:30 +0000332 /// \brief Mark the next token as consumed in \p State and modify its stacks
333 /// accordingly.
334 void moveStateToNextToken(IndentState &State) {
335 unsigned Index = State.ConsumedTokens;
336 const FormatToken &Current = Line.Tokens[Index];
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000337 unsigned ParenLevel = State.Indent.size() - 1;
338
339 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
340 State.FirstLessLess[ParenLevel] = State.Column;
341
Manuel Klimek95419382013-01-07 07:56:50 +0000342 State.Column += Current.TokenLength;
Daniel Jasper20409152012-12-04 14:54:30 +0000343
Daniel Jaspercf225b62012-12-24 13:43:52 +0000344 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000345 // prepare for the following tokens.
346 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000347 Current.Tok.is(tok::l_brace) ||
Daniel Jasper71607512013-01-07 10:48:50 +0000348 Annotations[Index].Type == TT_TemplateOpener) {
Daniel Jasper20409152012-12-04 14:54:30 +0000349 State.Indent.push_back(4 + State.LastSpace.back());
350 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000351 State.FirstLessLess.push_back(0);
Daniel Jasper20409152012-12-04 14:54:30 +0000352 }
353
Daniel Jaspercf225b62012-12-24 13:43:52 +0000354 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000355 // stacks.
Daniel Jaspera88bb452012-12-04 10:50:12 +0000356 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jaspercf225b62012-12-24 13:43:52 +0000357 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jasper71607512013-01-07 10:48:50 +0000358 Annotations[Index].Type == TT_TemplateCloser) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000359 State.Indent.pop_back();
360 State.LastSpace.pop_back();
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000361 State.FirstLessLess.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000362 }
363
364 ++State.ConsumedTokens;
365 }
366
Nico Weberdecf7bc2013-01-07 15:15:29 +0000367 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000368 unsigned splitPenalty(unsigned Index) {
369 assert(Index < Line.Tokens.size() &&
370 "Tried to calculate penalty for splitting after the last token");
371 const FormatToken &Left = Line.Tokens[Index];
372 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000373
374 // In for-loops, prefer breaking at ',' and ';'.
375 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
376 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
377 return 20;
378
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000379 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
380 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000381 return 0;
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000382 if (Left.Tok.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000383 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000384
Daniel Jasper9cda8002013-01-07 13:08:40 +0000385 prec::Level Level = getPrecedence(Left);
386
387 // Breaking after an assignment leads to a bad result as the two sides of
388 // the assignment are visually very close together.
389 if (Level == prec::Assignment)
390 return 50;
391
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000392 if (Level != prec::Unknown)
393 return Level;
394
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000395 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jasper46a46a22013-01-07 07:13:20 +0000396 return 150;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000397
Daniel Jasperbac016b2012-12-03 18:12:45 +0000398 return 3;
399 }
400
401 /// \brief Calculate the number of lines needed to format the remaining part
402 /// of the unwrapped line.
403 ///
404 /// Assumes the formatting so far has led to
405 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
406 /// added after the previous token.
407 ///
408 /// \param StopAt is used for optimization. If we can determine that we'll
409 /// definitely need at least \p StopAt additional lines, we already know of a
410 /// better solution.
411 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
412 // We are at the end of the unwrapped line, so we don't need any more lines.
413 if (State.ConsumedTokens >= Line.Tokens.size())
414 return 0;
415
416 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
417 return UINT_MAX;
418 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
419 return UINT_MAX;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000420 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
421 State.LineContainsContinuedForLoopSection)
422 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000423
Daniel Jasper33182dd2012-12-05 14:57:28 +0000424 unsigned CurrentPenalty = 0;
425 if (NewLine) {
426 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasperd7610b82012-12-24 16:51:15 +0000427 splitPenalty(State.ConsumedTokens - 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000428 } else {
429 if (State.Indent.size() < State.StartOfLineLevel)
430 CurrentPenalty += Parameters.PenaltyLevelDecrease *
431 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000432 }
433
Daniel Jasper20409152012-12-04 14:54:30 +0000434 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000435
436 // Exceeding column limit is bad.
Manuel Klimek060143e2013-01-02 18:33:23 +0000437 if (State.Column > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000438 return UINT_MAX;
439
Daniel Jasperbac016b2012-12-03 18:12:45 +0000440 if (StopAt <= CurrentPenalty)
441 return UINT_MAX;
442 StopAt -= CurrentPenalty;
443
Daniel Jasperbac016b2012-12-03 18:12:45 +0000444 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000445 if (I != Memory.end()) {
446 // If this state has already been examined, we can safely return the
447 // previous result if we
448 // - have not hit the optimatization (and thus returned UINT_MAX) OR
449 // - are now computing for a smaller or equal StopAt.
450 unsigned SavedResult = I->second.first;
451 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000452 if (SavedResult != UINT_MAX)
453 return SavedResult + CurrentPenalty;
454 else if (StopAt <= SavedStopAt)
455 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000456 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457
458 unsigned NoBreak = calcPenalty(State, false, StopAt);
459 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
460 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000461
462 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
463 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000464 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000465
466 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000467 }
468
469 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
470 /// each \c FormatToken.
471 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
472 unsigned Spaces) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000473 Replaces.insert(tooling::Replacement(
474 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
475 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
476 }
477
478 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
479 /// backslashes to escape newlines inside a preprocessor directive.
480 ///
481 /// This function and \c replaceWhitespace have the same behavior if
482 /// \c Newlines == 0.
483 void replacePPWhitespace(const FormatToken &Tok, unsigned NewLines,
484 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka080a182013-01-02 16:30:12 +0000485 std::string NewLineText;
Manuel Klimek060143e2013-01-02 18:33:23 +0000486 if (NewLines > 0) {
Daniel Jaspercd162382013-01-07 13:26:07 +0000487 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
488 WhitespaceStartColumn);
Manuel Klimeka080a182013-01-02 16:30:12 +0000489 for (unsigned i = 0; i < NewLines; ++i) {
490 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
491 NewLineText += "\\\n";
492 Offset = 0;
493 }
494 }
Daniel Jaspercd162382013-01-07 13:26:07 +0000495 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
496 Tok.WhiteSpaceLength, NewLineText +
497 std::string(Spaces, ' ')));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000498 }
499
500 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienko720ffb62012-12-05 13:56:52 +0000501 /// of the \c UnwrappedLine if there was no structural parsing error.
502 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000503 unsigned formatFirstToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000504 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000505 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
506 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
507
Daniel Jaspercd162382013-01-07 13:26:07 +0000508 unsigned Newlines = std::min(Token.NewlinesBefore,
509 Style.MaxEmptyLinesToKeep + 1);
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000510 if (Newlines == 0 && !Token.IsFirst)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000511 Newlines = 1;
512 unsigned Indent = Line.Level * 2;
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000513 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
514 Token.Tok.is(tok::kw_private)) &&
515 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000516 Indent += Style.AccessModifierOffset;
Manuel Klimek060143e2013-01-02 18:33:23 +0000517 if (!Line.InPPDirective || Token.HasUnescapedNewline)
518 replaceWhitespace(Token, Newlines, Indent);
519 else
Manuel Klimekd4397b92013-01-04 23:34:14 +0000520 replacePPWhitespace(Token, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000521 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000522 }
523
524 FormatStyle Style;
525 SourceManager &SourceMgr;
526 const UnwrappedLine &Line;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000527 const unsigned PreviousEndOfLineColumn;
Daniel Jasper71607512013-01-07 10:48:50 +0000528 const LineType CurrentLineType;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000529 const std::vector<TokenAnnotation> &Annotations;
530 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000531 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000532
Daniel Jasper33182dd2012-12-05 14:57:28 +0000533 // A map from an indent state to a pair (Result, Used-StopAt).
534 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
535 StateMap Memory;
536
Daniel Jasperbac016b2012-12-03 18:12:45 +0000537 OptimizationParameters Parameters;
538};
539
540/// \brief Determines extra information about the tokens comprising an
541/// \c UnwrappedLine.
542class TokenAnnotator {
543public:
544 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000545 SourceManager &SourceMgr, Lexer &Lex)
546 : Line(Line), Style(Style), SourceMgr(SourceMgr), Lex(Lex) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000547 }
548
549 /// \brief A parser that gathers additional information about tokens.
550 ///
551 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
552 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
553 /// into template parameter lists.
554 class AnnotatingParser {
555 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000556 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000557 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper71607512013-01-07 10:48:50 +0000558 : Tokens(Tokens), Annotations(Annotations), Index(0),
559 KeywordVirtualFound(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560 }
561
Daniel Jasper20409152012-12-04 14:54:30 +0000562 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000563 while (Index < Tokens.size()) {
564 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000565 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000566 next();
567 return true;
568 }
569 if (Tokens[Index].Tok.is(tok::r_paren) ||
Daniel Jasper1f42f112013-01-04 18:52:56 +0000570 Tokens[Index].Tok.is(tok::r_square) ||
571 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000572 return false;
573 if (Tokens[Index].Tok.is(tok::pipepipe) ||
574 Tokens[Index].Tok.is(tok::ampamp) ||
575 Tokens[Index].Tok.is(tok::question) ||
576 Tokens[Index].Tok.is(tok::colon))
577 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000578 if (!consumeToken())
579 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000580 }
581 return false;
582 }
583
Daniel Jasper20409152012-12-04 14:54:30 +0000584 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000585 while (Index < Tokens.size()) {
586 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000587 next();
588 return true;
589 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000590 if (Tokens[Index].Tok.is(tok::r_square) ||
591 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000593 if (!consumeToken())
594 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000595 }
596 return false;
597 }
598
Daniel Jasper20409152012-12-04 14:54:30 +0000599 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000600 while (Index < Tokens.size()) {
601 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000602 next();
603 return true;
604 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000605 if (Tokens[Index].Tok.is(tok::r_paren) ||
606 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000607 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000608 if (!consumeToken())
609 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000610 }
611 return false;
612 }
613
Daniel Jasper20409152012-12-04 14:54:30 +0000614 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000615 while (Index < Tokens.size()) {
616 if (Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000617 Annotations[Index].Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618 next();
619 return true;
620 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000621 if (!consumeToken())
622 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000623 }
624 return false;
625 }
626
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000627 bool parseTemplateDeclaration() {
628 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000629 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000630 next();
631 if (!parseAngle())
632 return false;
633 Annotations[Index - 1].ClosesTemplateDeclaration = true;
634 parseLine();
635 return true;
636 }
637 return false;
638 }
639
Daniel Jasper1f42f112013-01-04 18:52:56 +0000640 bool consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000641 unsigned CurrentIndex = Index;
642 next();
643 switch (Tokens[CurrentIndex].Tok.getKind()) {
644 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000645 if (!parseParens())
646 return false;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000647 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000648 Annotations[Index].Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000649 next();
650 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000651 break;
652 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000653 if (!parseSquare())
654 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000655 break;
656 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000657 if (parseAngle())
Daniel Jasper71607512013-01-07 10:48:50 +0000658 Annotations[CurrentIndex].Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000659 else {
Daniel Jasper71607512013-01-07 10:48:50 +0000660 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000661 Index = CurrentIndex + 1;
662 }
663 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000664 case tok::r_paren:
665 case tok::r_square:
666 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000667 case tok::greater:
Daniel Jasper71607512013-01-07 10:48:50 +0000668 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000669 break;
670 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000671 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000672 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000673 next();
674 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000675 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000676 next();
677 }
678 } else {
679 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000680 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000681 next();
682 }
683 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000684 break;
685 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000686 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000687 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000688 case tok::kw_template:
689 parseTemplateDeclaration();
690 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000691 default:
692 break;
693 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000694 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000695 }
696
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000697 void parseIncludeDirective() {
698 while (Index < Tokens.size()) {
699 if (Tokens[Index].Tok.is(tok::slash))
Daniel Jasper71607512013-01-07 10:48:50 +0000700 Annotations[Index].Type = TT_DirectorySeparator;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000701 else if (Tokens[Index].Tok.is(tok::less))
Daniel Jasper71607512013-01-07 10:48:50 +0000702 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000703 else if (Tokens[Index].Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000704 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000705 next();
706 }
707 }
708
709 void parsePreprocessorDirective() {
710 next();
711 if (Index >= Tokens.size())
712 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000713 // Hashes in the middle of a line can lead to any strange token
714 // sequence.
715 if (Tokens[Index].Tok.getIdentifierInfo() == NULL)
716 return;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000717 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
718 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000719 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000720 parseIncludeDirective();
721 break;
722 default:
723 break;
724 }
725 }
726
Daniel Jasper71607512013-01-07 10:48:50 +0000727 LineType parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000728 if (Tokens[Index].Tok.is(tok::hash)) {
729 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000730 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000731 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732 while (Index < Tokens.size()) {
Daniel Jasper71607512013-01-07 10:48:50 +0000733 if (Tokens[Index].Tok.is(tok::kw_virtual))
734 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000735 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000736 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000737 }
Daniel Jasper71607512013-01-07 10:48:50 +0000738 if (KeywordVirtualFound)
739 return LT_VirtualFunctionDecl;
740 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 }
742
743 void next() {
744 ++Index;
745 }
746
747 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000748 const SmallVector<FormatToken, 16> &Tokens;
749 std::vector<TokenAnnotation> &Annotations;
750 unsigned Index;
Daniel Jasper71607512013-01-07 10:48:50 +0000751 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000752 };
753
Daniel Jasper1f42f112013-01-04 18:52:56 +0000754 bool annotate() {
Daniel Jasper71607512013-01-07 10:48:50 +0000755 if (Line.Tokens.size() == 0)
756 return true;
757
Daniel Jasperbac016b2012-12-03 18:12:45 +0000758 Annotations.clear();
759 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
760 Annotations.push_back(TokenAnnotation());
761 }
762
Manuel Klimek0be4b362012-12-03 20:55:42 +0000763 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasper71607512013-01-07 10:48:50 +0000764 CurrentLineType = Parser.parseLine();
765 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000766 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000767
768 determineTokenTypes();
Daniel Jasper71607512013-01-07 10:48:50 +0000769
770 if (Annotations[0].Type == TT_ObjCMethodSpecifier)
771 CurrentLineType = LT_ObjCMethodDecl;
772
Daniel Jasperbac016b2012-12-03 18:12:45 +0000773 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
774 TokenAnnotation &Annotation = Annotations[i];
775
Daniel Jasperda927712013-01-07 15:36:15 +0000776 Annotation.SpaceRequiredBefore = spaceRequiredBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000777
Daniel Jasperda927712013-01-07 15:36:15 +0000778 if (Annotation.Type == TT_CtorInitializerColon ||
779 Annotations[i - 1].Type == TT_LineComment ||
780 (Line.Tokens[i].Tok.is(tok::string_literal) &&
781 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000782 Annotation.MustBreakBefore = true;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000783 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000784 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000785 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000786 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000787 Annotation.MustBreakBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000788 }
789
Daniel Jasperda927712013-01-07 15:36:15 +0000790 Annotation.CanBreakBefore = Annotation.MustBreakBefore ||
791 canBreakBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000792 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000793 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000794 }
795
Daniel Jasper71607512013-01-07 10:48:50 +0000796 LineType getLineType() {
797 return CurrentLineType;
798 }
799
Daniel Jasperbac016b2012-12-03 18:12:45 +0000800 const std::vector<TokenAnnotation> &getAnnotations() {
801 return Annotations;
802 }
803
804private:
805 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000806 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000807 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
808 TokenAnnotation &Annotation = Annotations[i];
809 const FormatToken &Tok = Line.Tokens[i];
810
Nico Webera9ccdd12013-01-07 16:36:17 +0000811 if (getPrecedence(Tok) == prec::Assignment ||
812 Tok.Tok.is(tok::kw_return) || Tok.Tok.is(tok::kw_throw))
Nico Weber00d5a042012-12-23 01:07:46 +0000813 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000814
Daniel Jasper71607512013-01-07 10:48:50 +0000815 if (Annotation.Type != TT_Unknown)
Daniel Jasper675d2e32012-12-21 10:20:02 +0000816 continue;
817
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000818 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000819 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000820 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
821 Annotation.Type = determinePlusMinusUsage(i);
822 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
823 Annotation.Type = determineIncrementUsage(i);
824 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000825 Annotation.Type = TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000826 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasper71607512013-01-07 10:48:50 +0000827 Annotation.Type = TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000828 } else if (Tok.Tok.is(tok::comment)) {
Manuel Klimek6cf58142013-01-07 08:54:53 +0000829 std::string Data(
830 Lexer::getSpelling(Tok.Tok, SourceMgr, Lex.getLangOpts()));
831 if (StringRef(Data).startswith("//"))
Daniel Jasper71607512013-01-07 10:48:50 +0000832 Annotation.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000833 else
Daniel Jasper71607512013-01-07 10:48:50 +0000834 Annotation.Type = TT_BlockComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000835 }
836 }
837 }
838
Daniel Jasperbac016b2012-12-03 18:12:45 +0000839 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000840 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000841 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000842 }
843
Daniel Jasper71607512013-01-07 10:48:50 +0000844 TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperba3d3072013-01-02 17:21:36 +0000845 if (Index == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000846 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000847 if (Index == Annotations.size())
Daniel Jasper71607512013-01-07 10:48:50 +0000848 return TT_Unknown;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000849 const FormatToken &PrevToken = Line.Tokens[Index - 1];
850 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000851
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000852 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
853 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
854 PrevToken.Tok.is(tok::colon) ||
Daniel Jasper71607512013-01-07 10:48:50 +0000855 Annotations[Index - 1].Type == TT_BinaryOperator)
856 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000857
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000858 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000859 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
860 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
861 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
862 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000863 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000864
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000865 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
866 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000867 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000868
Daniel Jasper112fb272012-12-05 07:51:39 +0000869 // It is very unlikely that we are going to find a pointer or reference type
870 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000871 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000872 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000873
Daniel Jasper71607512013-01-07 10:48:50 +0000874 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875 }
876
Daniel Jasper71607512013-01-07 10:48:50 +0000877 TokenType determinePlusMinusUsage(unsigned Index) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000878 // At the start of the line, +/- specific ObjectiveC method declarations.
879 if (Index == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000880 return TT_ObjCMethodSpecifier;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000881
882 // Use heuristics to recognize unary operators.
883 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
884 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
885 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasper1f0754b2013-01-02 15:26:16 +0000886 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
887 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper71607512013-01-07 10:48:50 +0000888 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000889
890 // There can't be to consecutive binary operators.
Daniel Jasper71607512013-01-07 10:48:50 +0000891 if (Annotations[Index - 1].Type == TT_BinaryOperator)
892 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000893
894 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +0000895 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000896 }
897
898 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper71607512013-01-07 10:48:50 +0000899 TokenType determineIncrementUsage(unsigned Index) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000900 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +0000901 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000902
Daniel Jasper71607512013-01-07 10:48:50 +0000903 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000904 }
905
906 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000907 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
908 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000909 if (Left.is(tok::kw_template) && Right.is(tok::less))
910 return true;
911 if (Left.is(tok::arrow) || Right.is(tok::arrow))
912 return false;
913 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
914 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000915 if (Left.is(tok::at) && Right.is(tok::identifier))
916 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000917 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
918 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000919 if (Right.is(tok::amp) || Right.is(tok::star))
920 return Left.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000921 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
922 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000923 if (Left.is(tok::amp) || Left.is(tok::star))
924 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
925 if (Right.is(tok::star) && Left.is(tok::l_paren))
926 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000927 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
928 Right.is(tok::r_square))
929 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000930 if (Left.is(tok::coloncolon) ||
931 (Right.is(tok::coloncolon) &&
932 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000933 return false;
934 if (Left.is(tok::period) || Right.is(tok::period))
935 return false;
936 if (Left.is(tok::colon) || Right.is(tok::colon))
937 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000938 if (Left.is(tok::l_paren))
939 return false;
940 if (Left.is(tok::hash))
941 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000942 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000943 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000944 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
945 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasperba3d3072013-01-02 17:21:36 +0000946 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000947 }
Nico Weberd0af4b42013-01-07 16:14:28 +0000948 if (Left.is(tok::at) && Right.getObjCKeywordID() != tok::objc_not_keyword)
949 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000950 return true;
951 }
952
Daniel Jasperda927712013-01-07 15:36:15 +0000953 bool spaceRequiredBefore(unsigned i) {
954 TokenAnnotation &Annotation = Annotations[i];
955 const FormatToken &Current = Line.Tokens[i];
956
957 if (CurrentLineType == LT_ObjCMethodDecl) {
958 if (Current.Tok.is(tok::identifier) && (i != Line.Tokens.size() - 1) &&
959 Line.Tokens[i + 1].Tok.is(tok::colon) &&
960 Line.Tokens[i - 1].Tok.is(tok::identifier))
961 return true;
962 if (Current.Tok.is(tok::colon))
963 return false;
964 if (Annotations[i - 1].Type == TT_ObjCMethodSpecifier)
965 return true;
966 if (Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
967 Current.Tok.is(tok::identifier))
968 // Don't space between ')' and <id>
969 return false;
970 if (Line.Tokens[i - 1].Tok.is(tok::colon) && Current.Tok.is(tok::l_paren))
971 // Don't space between ':' and '('
972 return false;
973 }
974
975 if (Annotation.Type == TT_CtorInitializerColon)
976 return true;
977 if (Annotation.Type == TT_OverloadedOperator)
978 return Current.Tok.is(tok::identifier) || Current.Tok.is(tok::kw_new) ||
979 Current.Tok.is(tok::kw_delete);
980 if (Annotations[i - 1].Type == TT_OverloadedOperator)
981 return false;
982 if (Current.Tok.is(tok::colon))
983 return Line.Tokens[0].Tok.isNot(tok::kw_case) &&
984 (i != Line.Tokens.size() - 1);
985 if (Annotations[i - 1].Type == TT_UnaryOperator)
986 return false;
987 if (Annotation.Type == TT_UnaryOperator)
988 return Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
989 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
990 if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
991 Current.Tok.is(tok::greater)) {
992 return Annotation.Type == TT_TemplateCloser && Annotations[i - 1].Type ==
993 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
994 }
995 if (Annotation.Type == TT_DirectorySeparator ||
996 Annotations[i - 1].Type == TT_DirectorySeparator)
997 return false;
998 if (Annotation.Type == TT_BinaryOperator ||
999 Annotations[i - 1].Type == TT_BinaryOperator)
1000 return true;
1001 if (Annotations[i - 1].Type == TT_TemplateCloser &&
1002 Current.Tok.is(tok::l_paren))
1003 return false;
1004 if (Current.Tok.is(tok::less) && Line.Tokens[0].Tok.is(tok::hash))
1005 return true;
1006 if (Annotation.Type == TT_TrailingUnaryOperator)
1007 return false;
1008 return spaceRequiredBetween(Line.Tokens[i - 1].Tok, Current.Tok);
1009 }
1010
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001011 bool canBreakBefore(unsigned i) {
Daniel Jasperda927712013-01-07 15:36:15 +00001012 if (CurrentLineType == LT_ObjCMethodDecl) {
1013 if (Line.Tokens[i].Tok.is(tok::identifier) &&
1014 (i != Line.Tokens.size() - 1) &&
1015 Line.Tokens[i + 1].Tok.is(tok::colon) &&
1016 Line.Tokens[i - 1].Tok.is(tok::identifier))
1017 return true;
1018 if (CurrentLineType == LT_ObjCMethodDecl &&
1019 Line.Tokens[i].Tok.is(tok::identifier) &&
1020 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
1021 Line.Tokens[i - 2].Tok.is(tok::colon))
1022 // Don't break this identifier as ':' or identifier
1023 // before it will break.
1024 return false;
1025 if (Line.Tokens[i].Tok.is(tok::colon) &&
1026 Line.Tokens[i - 1].Tok.is(tok::identifier) &&
1027 Annotations[i - 1].CanBreakBefore)
1028 // Don't break at ':' if identifier before it can beak.
1029 return false;
1030 }
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001031 if (Annotations[i - 1].ClosesTemplateDeclaration)
1032 return true;
Daniel Jasper71607512013-01-07 10:48:50 +00001033 if (Annotations[i - 1].Type == TT_PointerOrReference ||
1034 Annotations[i - 1].Type == TT_TemplateCloser ||
1035 Annotations[i].Type == TT_ConditionalExpr) {
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001036 return false;
1037 }
1038 const FormatToken &Left = Line.Tokens[i - 1];
1039 const FormatToken &Right = Line.Tokens[i];
Daniel Jasper71607512013-01-07 10:48:50 +00001040 if (Left.Tok.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
1041 return false;
1042
Daniel Jasper05b1ac82012-12-17 11:29:41 +00001043 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
1044 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001045 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +00001046 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001047 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
1048 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
1049 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
1050 Left.Tok.is(tok::l_brace) ||
1051 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001052 }
1053
1054 const UnwrappedLine &Line;
1055 FormatStyle Style;
1056 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001057 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001058 LineType CurrentLineType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001059 std::vector<TokenAnnotation> Annotations;
1060};
1061
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001062class LexerBasedFormatTokenSource : public FormatTokenSource {
1063public:
1064 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001065 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001066 IdentTable(Lex.getLangOpts()) {
1067 Lex.SetKeepWhitespaceMode(true);
1068 }
1069
1070 virtual FormatToken getNextToken() {
1071 if (GreaterStashed) {
1072 FormatTok.NewlinesBefore = 0;
1073 FormatTok.WhiteSpaceStart =
1074 FormatTok.Tok.getLocation().getLocWithOffset(1);
1075 FormatTok.WhiteSpaceLength = 0;
1076 GreaterStashed = false;
1077 return FormatTok;
1078 }
1079
1080 FormatTok = FormatToken();
1081 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001082 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001083 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001084 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1085 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001086
1087 // Consume and record whitespace until we find a significant token.
1088 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001089 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001090 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1091 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001092 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1093
1094 if (FormatTok.Tok.is(tok::eof))
1095 return FormatTok;
1096 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001097 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001098 }
Manuel Klimek95419382013-01-07 07:56:50 +00001099
1100 // Now FormatTok is the next non-whitespace token.
1101 FormatTok.TokenLength = Text.size();
1102
Manuel Klimekd4397b92013-01-04 23:34:14 +00001103 // In case the token starts with escaped newlines, we want to
1104 // take them into account as whitespace - this pattern is quite frequent
1105 // in macro definitions.
1106 // FIXME: What do we want to do with other escaped spaces, and escaped
1107 // spaces or newlines in the middle of tokens?
1108 // FIXME: Add a more explicit test.
1109 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001110 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001111 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001112 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001113 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001114 }
1115
1116 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001117 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001118 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001119 FormatTok.Tok.setKind(Info.getTokenID());
1120 }
1121
1122 if (FormatTok.Tok.is(tok::greatergreater)) {
1123 FormatTok.Tok.setKind(tok::greater);
1124 GreaterStashed = true;
1125 }
1126
1127 return FormatTok;
1128 }
1129
1130private:
1131 FormatToken FormatTok;
1132 bool GreaterStashed;
1133 Lexer &Lex;
1134 SourceManager &SourceMgr;
1135 IdentifierTable IdentTable;
1136
1137 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001138 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001139 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1140 Tok.getLength());
1141 }
1142};
1143
Daniel Jasperbac016b2012-12-03 18:12:45 +00001144class Formatter : public UnwrappedLineConsumer {
1145public:
1146 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1147 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001148 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001149 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001150 }
1151
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001152 virtual ~Formatter() {
1153 }
1154
Daniel Jasperbac016b2012-12-03 18:12:45 +00001155 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001156 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1157 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001158 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001159 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001160 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1161 E = UnwrappedLines.end();
1162 I != E; ++I)
Daniel Jaspercd162382013-01-07 13:26:07 +00001163 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1164 PreviousEndOfLineColumn);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001165 return Replaces;
1166 }
1167
1168private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001169 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001170 UnwrappedLines.push_back(TheLine);
1171 }
1172
Manuel Klimekd4397b92013-01-04 23:34:14 +00001173 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1174 unsigned PreviousEndOfLineColumn) {
1175 if (TheLine.Tokens.empty())
Daniel Jaspercd162382013-01-07 13:26:07 +00001176 return 0; // FIXME: Find out how this can ever happen.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001177
Daniel Jaspercd162382013-01-07 13:26:07 +00001178 CharSourceRange LineRange = CharSourceRange::getTokenRange(
1179 TheLine.Tokens.front().Tok.getLocation(),
1180 TheLine.Tokens.back().Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001181
1182 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1183 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1184 Ranges[i].getBegin()) ||
1185 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1186 LineRange.getBegin()))
1187 continue;
1188
Manuel Klimek6cf58142013-01-07 08:54:53 +00001189 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasper1f42f112013-01-04 18:52:56 +00001190 if (!Annotator.annotate())
Manuel Klimekd4397b92013-01-04 23:34:14 +00001191 break;
1192 UnwrappedLineFormatter Formatter(
1193 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
Daniel Jasper71607512013-01-07 10:48:50 +00001194 Annotator.getLineType(), Annotator.getAnnotations(), Replaces,
1195 StructuralError);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001196 return Formatter.format();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001197 }
Manuel Klimekd4397b92013-01-04 23:34:14 +00001198 // If we did not reformat this unwrapped line, the column at the end of the
1199 // last token is unchanged - thus, we can calculate the end of the last
1200 // token, and return the result.
1201 const FormatToken &Token = TheLine.Tokens.back();
1202 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) +
1203 Lex.MeasureTokenLength(Token.Tok.getLocation(), SourceMgr,
1204 Lex.getLangOpts()) -
1205 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001206 }
1207
1208 FormatStyle Style;
1209 Lexer &Lex;
1210 SourceManager &SourceMgr;
1211 tooling::Replacements Replaces;
1212 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001213 std::vector<UnwrappedLine> UnwrappedLines;
1214 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001215};
1216
1217tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1218 SourceManager &SourceMgr,
1219 std::vector<CharSourceRange> Ranges) {
1220 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1221 return formatter.format();
1222}
1223
Daniel Jaspercd162382013-01-07 13:26:07 +00001224} // namespace format
1225} // namespace clang