blob: 5c433834c843956f39c3bbb264c2bc444f4bcd27 [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;
Nico Weber6092d4e2013-01-07 19:05:19 +0000513
514 bool IsAccessModifier = false;
515 if (Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
516 Token.Tok.is(tok::kw_private))
517 IsAccessModifier = true;
518 else if (Token.Tok.is(tok::at) && Line.Tokens.size() > 1 &&
519 (Line.Tokens[1].Tok.isObjCAtKeyword(tok::objc_public) ||
520 Line.Tokens[1].Tok.isObjCAtKeyword(tok::objc_protected) ||
521 Line.Tokens[1].Tok.isObjCAtKeyword(tok::objc_package) ||
522 Line.Tokens[1].Tok.isObjCAtKeyword(tok::objc_private)))
523 IsAccessModifier = true;
524
525 if (IsAccessModifier &&
Alexander Kornienko56e49c52012-12-10 16:34:48 +0000526 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000527 Indent += Style.AccessModifierOffset;
Manuel Klimek060143e2013-01-02 18:33:23 +0000528 if (!Line.InPPDirective || Token.HasUnescapedNewline)
529 replaceWhitespace(Token, Newlines, Indent);
530 else
Manuel Klimekd4397b92013-01-04 23:34:14 +0000531 replacePPWhitespace(Token, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000532 return Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000533 }
534
535 FormatStyle Style;
536 SourceManager &SourceMgr;
537 const UnwrappedLine &Line;
Manuel Klimekd4397b92013-01-04 23:34:14 +0000538 const unsigned PreviousEndOfLineColumn;
Daniel Jasper71607512013-01-07 10:48:50 +0000539 const LineType CurrentLineType;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000540 const std::vector<TokenAnnotation> &Annotations;
541 tooling::Replacements &Replaces;
Alexander Kornienkocff563c2012-12-04 17:27:50 +0000542 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000543
Daniel Jasper33182dd2012-12-05 14:57:28 +0000544 // A map from an indent state to a pair (Result, Used-StopAt).
545 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
546 StateMap Memory;
547
Daniel Jasperbac016b2012-12-03 18:12:45 +0000548 OptimizationParameters Parameters;
549};
550
551/// \brief Determines extra information about the tokens comprising an
552/// \c UnwrappedLine.
553class TokenAnnotator {
554public:
555 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimek6cf58142013-01-07 08:54:53 +0000556 SourceManager &SourceMgr, Lexer &Lex)
557 : Line(Line), Style(Style), SourceMgr(SourceMgr), Lex(Lex) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000558 }
559
560 /// \brief A parser that gathers additional information about tokens.
561 ///
562 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
563 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
564 /// into template parameter lists.
565 class AnnotatingParser {
566 public:
Manuel Klimek0be4b362012-12-03 20:55:42 +0000567 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperbac016b2012-12-03 18:12:45 +0000568 std::vector<TokenAnnotation> &Annotations)
Daniel Jasper71607512013-01-07 10:48:50 +0000569 : Tokens(Tokens), Annotations(Annotations), Index(0),
570 KeywordVirtualFound(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000571 }
572
Daniel Jasper20409152012-12-04 14:54:30 +0000573 bool parseAngle() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000574 while (Index < Tokens.size()) {
575 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000576 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000577 next();
578 return true;
579 }
580 if (Tokens[Index].Tok.is(tok::r_paren) ||
Daniel Jasper1f42f112013-01-04 18:52:56 +0000581 Tokens[Index].Tok.is(tok::r_square) ||
582 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000583 return false;
584 if (Tokens[Index].Tok.is(tok::pipepipe) ||
585 Tokens[Index].Tok.is(tok::ampamp) ||
586 Tokens[Index].Tok.is(tok::question) ||
587 Tokens[Index].Tok.is(tok::colon))
588 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000589 if (!consumeToken())
590 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000591 }
592 return false;
593 }
594
Daniel Jasper20409152012-12-04 14:54:30 +0000595 bool parseParens() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000596 while (Index < Tokens.size()) {
597 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000598 next();
599 return true;
600 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000601 if (Tokens[Index].Tok.is(tok::r_square) ||
602 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000603 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000604 if (!consumeToken())
605 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000606 }
607 return false;
608 }
609
Daniel Jasper20409152012-12-04 14:54:30 +0000610 bool parseSquare() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000611 while (Index < Tokens.size()) {
612 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000613 next();
614 return true;
615 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000616 if (Tokens[Index].Tok.is(tok::r_paren) ||
617 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000618 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000619 if (!consumeToken())
620 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000621 }
622 return false;
623 }
624
Daniel Jasper20409152012-12-04 14:54:30 +0000625 bool parseConditional() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000626 while (Index < Tokens.size()) {
627 if (Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000628 Annotations[Index].Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000629 next();
630 return true;
631 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000632 if (!consumeToken())
633 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000634 }
635 return false;
636 }
637
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000638 bool parseTemplateDeclaration() {
639 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000640 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000641 next();
642 if (!parseAngle())
643 return false;
644 Annotations[Index - 1].ClosesTemplateDeclaration = true;
645 parseLine();
646 return true;
647 }
648 return false;
649 }
650
Daniel Jasper1f42f112013-01-04 18:52:56 +0000651 bool consumeToken() {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000652 unsigned CurrentIndex = Index;
653 next();
654 switch (Tokens[CurrentIndex].Tok.getKind()) {
655 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000656 if (!parseParens())
657 return false;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000658 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000659 Annotations[Index].Type = TT_CtorInitializerColon;
Daniel Jasper1321eb52012-12-18 21:05:13 +0000660 next();
661 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000662 break;
663 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +0000664 if (!parseSquare())
665 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000666 break;
667 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +0000668 if (parseAngle())
Daniel Jasper71607512013-01-07 10:48:50 +0000669 Annotations[CurrentIndex].Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000670 else {
Daniel Jasper71607512013-01-07 10:48:50 +0000671 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000672 Index = CurrentIndex + 1;
673 }
674 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000675 case tok::r_paren:
676 case tok::r_square:
677 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000678 case tok::greater:
Daniel Jasper71607512013-01-07 10:48:50 +0000679 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000680 break;
681 case tok::kw_operator:
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000682 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000683 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000684 next();
685 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000686 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000687 next();
688 }
689 } else {
690 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000691 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +0000692 next();
693 }
694 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000695 break;
696 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +0000697 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000698 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +0000699 case tok::kw_template:
700 parseTemplateDeclaration();
701 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000702 default:
703 break;
704 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000705 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000706 }
707
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000708 void parseIncludeDirective() {
709 while (Index < Tokens.size()) {
710 if (Tokens[Index].Tok.is(tok::slash))
Daniel Jasper71607512013-01-07 10:48:50 +0000711 Annotations[Index].Type = TT_DirectorySeparator;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000712 else if (Tokens[Index].Tok.is(tok::less))
Daniel Jasper71607512013-01-07 10:48:50 +0000713 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000714 else if (Tokens[Index].Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000715 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000716 next();
717 }
718 }
719
720 void parsePreprocessorDirective() {
721 next();
722 if (Index >= Tokens.size())
723 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +0000724 // Hashes in the middle of a line can lead to any strange token
725 // sequence.
726 if (Tokens[Index].Tok.getIdentifierInfo() == NULL)
727 return;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000728 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
729 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +0000730 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000731 parseIncludeDirective();
732 break;
733 default:
734 break;
735 }
736 }
737
Daniel Jasper71607512013-01-07 10:48:50 +0000738 LineType parseLine() {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000739 if (Tokens[Index].Tok.is(tok::hash)) {
740 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +0000741 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000742 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000743 while (Index < Tokens.size()) {
Daniel Jasper71607512013-01-07 10:48:50 +0000744 if (Tokens[Index].Tok.is(tok::kw_virtual))
745 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000746 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +0000747 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000748 }
Daniel Jasper71607512013-01-07 10:48:50 +0000749 if (KeywordVirtualFound)
750 return LT_VirtualFunctionDecl;
751 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000752 }
753
754 void next() {
755 ++Index;
756 }
757
758 private:
Daniel Jasperbac016b2012-12-03 18:12:45 +0000759 const SmallVector<FormatToken, 16> &Tokens;
760 std::vector<TokenAnnotation> &Annotations;
761 unsigned Index;
Daniel Jasper71607512013-01-07 10:48:50 +0000762 bool KeywordVirtualFound;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000763 };
764
Daniel Jasper1f42f112013-01-04 18:52:56 +0000765 bool annotate() {
Daniel Jasper71607512013-01-07 10:48:50 +0000766 if (Line.Tokens.size() == 0)
767 return true;
768
Daniel Jasperbac016b2012-12-03 18:12:45 +0000769 Annotations.clear();
770 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
771 Annotations.push_back(TokenAnnotation());
772 }
773
Manuel Klimek0be4b362012-12-03 20:55:42 +0000774 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasper71607512013-01-07 10:48:50 +0000775 CurrentLineType = Parser.parseLine();
776 if (CurrentLineType == LT_Invalid)
Daniel Jasper1f42f112013-01-04 18:52:56 +0000777 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000778
779 determineTokenTypes();
Daniel Jasper71607512013-01-07 10:48:50 +0000780
781 if (Annotations[0].Type == TT_ObjCMethodSpecifier)
782 CurrentLineType = LT_ObjCMethodDecl;
783
Daniel Jasperbac016b2012-12-03 18:12:45 +0000784 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
785 TokenAnnotation &Annotation = Annotations[i];
786
Daniel Jasperda927712013-01-07 15:36:15 +0000787 Annotation.SpaceRequiredBefore = spaceRequiredBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000788
Daniel Jasperda927712013-01-07 15:36:15 +0000789 if (Annotation.Type == TT_CtorInitializerColon ||
790 Annotations[i - 1].Type == TT_LineComment ||
791 (Line.Tokens[i].Tok.is(tok::string_literal) &&
792 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000793 Annotation.MustBreakBefore = true;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000794 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000795 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000796 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian5f04ef52012-12-21 17:14:23 +0000797 // as in, @optional @property ...
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000798 Annotation.MustBreakBefore = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000799 }
800
Daniel Jasperda927712013-01-07 15:36:15 +0000801 Annotation.CanBreakBefore = Annotation.MustBreakBefore ||
802 canBreakBefore(i);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000804 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000805 }
806
Daniel Jasper71607512013-01-07 10:48:50 +0000807 LineType getLineType() {
808 return CurrentLineType;
809 }
810
Daniel Jasperbac016b2012-12-03 18:12:45 +0000811 const std::vector<TokenAnnotation> &getAnnotations() {
812 return Annotations;
813 }
814
815private:
816 void determineTokenTypes() {
Nico Weber00d5a042012-12-23 01:07:46 +0000817 bool IsRHS = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000818 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
819 TokenAnnotation &Annotation = Annotations[i];
820 const FormatToken &Tok = Line.Tokens[i];
821
Nico Webera9ccdd12013-01-07 16:36:17 +0000822 if (getPrecedence(Tok) == prec::Assignment ||
823 Tok.Tok.is(tok::kw_return) || Tok.Tok.is(tok::kw_throw))
Nico Weber00d5a042012-12-23 01:07:46 +0000824 IsRHS = true;
Daniel Jasper112fb272012-12-05 07:51:39 +0000825
Daniel Jasper71607512013-01-07 10:48:50 +0000826 if (Annotation.Type != TT_Unknown)
Daniel Jasper675d2e32012-12-21 10:20:02 +0000827 continue;
828
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000829 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber00d5a042012-12-23 01:07:46 +0000830 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000831 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
832 Annotation.Type = determinePlusMinusUsage(i);
833 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
834 Annotation.Type = determineIncrementUsage(i);
835 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasper71607512013-01-07 10:48:50 +0000836 Annotation.Type = TT_UnaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000837 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasper71607512013-01-07 10:48:50 +0000838 Annotation.Type = TT_BinaryOperator;
Daniel Jasper675d2e32012-12-21 10:20:02 +0000839 } else if (Tok.Tok.is(tok::comment)) {
Manuel Klimek6cf58142013-01-07 08:54:53 +0000840 std::string Data(
841 Lexer::getSpelling(Tok.Tok, SourceMgr, Lex.getLangOpts()));
842 if (StringRef(Data).startswith("//"))
Daniel Jasper71607512013-01-07 10:48:50 +0000843 Annotation.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000844 else
Daniel Jasper71607512013-01-07 10:48:50 +0000845 Annotation.Type = TT_BlockComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000846 }
847 }
848 }
849
Daniel Jasperbac016b2012-12-03 18:12:45 +0000850 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +0000851 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +0000852 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000853 }
854
Daniel Jasper71607512013-01-07 10:48:50 +0000855 TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasperba3d3072013-01-02 17:21:36 +0000856 if (Index == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000857 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000858 if (Index == Annotations.size())
Daniel Jasper71607512013-01-07 10:48:50 +0000859 return TT_Unknown;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000860 const FormatToken &PrevToken = Line.Tokens[Index - 1];
861 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperbac016b2012-12-03 18:12:45 +0000862
Daniel Jasper9bb0d282013-01-04 20:46:38 +0000863 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
864 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
865 PrevToken.Tok.is(tok::colon) ||
Daniel Jasper71607512013-01-07 10:48:50 +0000866 Annotations[Index - 1].Type == TT_BinaryOperator)
867 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000868
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000869 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasperba3d3072013-01-02 17:21:36 +0000870 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
871 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
872 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
873 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +0000874 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000876 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
877 NextToken.Tok.is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +0000878 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +0000879
Daniel Jasper112fb272012-12-05 07:51:39 +0000880 // It is very unlikely that we are going to find a pointer or reference type
881 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +0000882 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +0000883 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +0000884
Daniel Jasper71607512013-01-07 10:48:50 +0000885 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000886 }
887
Daniel Jasper71607512013-01-07 10:48:50 +0000888 TokenType determinePlusMinusUsage(unsigned Index) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000889 // At the start of the line, +/- specific ObjectiveC method declarations.
890 if (Index == 0)
Daniel Jasper71607512013-01-07 10:48:50 +0000891 return TT_ObjCMethodSpecifier;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000892
893 // Use heuristics to recognize unary operators.
894 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
895 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
896 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasper1f0754b2013-01-02 15:26:16 +0000897 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
898 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasper71607512013-01-07 10:48:50 +0000899 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000900
901 // There can't be to consecutive binary operators.
Daniel Jasper71607512013-01-07 10:48:50 +0000902 if (Annotations[Index - 1].Type == TT_BinaryOperator)
903 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000904
905 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +0000906 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000907 }
908
909 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper71607512013-01-07 10:48:50 +0000910 TokenType determineIncrementUsage(unsigned Index) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000911 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +0000912 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000913
Daniel Jasper71607512013-01-07 10:48:50 +0000914 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000915 }
916
917 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jasper8b39c662012-12-10 18:59:13 +0000918 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
919 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000920 if (Left.is(tok::kw_template) && Right.is(tok::less))
921 return true;
922 if (Left.is(tok::arrow) || Right.is(tok::arrow))
923 return false;
924 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
925 return false;
Fariborz Jahanian154120c2012-12-20 19:54:13 +0000926 if (Left.is(tok::at) && Right.is(tok::identifier))
927 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000928 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
929 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000930 if (Right.is(tok::amp) || Right.is(tok::star))
931 return Left.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000932 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
933 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000934 if (Left.is(tok::amp) || Left.is(tok::star))
935 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
936 if (Right.is(tok::star) && Left.is(tok::l_paren))
937 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000938 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
939 Right.is(tok::r_square))
940 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +0000941 if (Left.is(tok::coloncolon) ||
942 (Right.is(tok::coloncolon) &&
943 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000944 return false;
945 if (Left.is(tok::period) || Right.is(tok::period))
946 return false;
947 if (Left.is(tok::colon) || Right.is(tok::colon))
948 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000949 if (Left.is(tok::l_paren))
950 return false;
951 if (Left.is(tok::hash))
952 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000953 if (Right.is(tok::l_paren)) {
Daniel Jasper98e6b4a2012-12-21 09:41:31 +0000954 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +0000955 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
956 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasperba3d3072013-01-02 17:21:36 +0000957 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperbac016b2012-12-03 18:12:45 +0000958 }
Nico Weberd0af4b42013-01-07 16:14:28 +0000959 if (Left.is(tok::at) && Right.getObjCKeywordID() != tok::objc_not_keyword)
960 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000961 return true;
962 }
963
Daniel Jasperda927712013-01-07 15:36:15 +0000964 bool spaceRequiredBefore(unsigned i) {
965 TokenAnnotation &Annotation = Annotations[i];
966 const FormatToken &Current = Line.Tokens[i];
967
968 if (CurrentLineType == LT_ObjCMethodDecl) {
969 if (Current.Tok.is(tok::identifier) && (i != Line.Tokens.size() - 1) &&
970 Line.Tokens[i + 1].Tok.is(tok::colon) &&
971 Line.Tokens[i - 1].Tok.is(tok::identifier))
972 return true;
973 if (Current.Tok.is(tok::colon))
974 return false;
975 if (Annotations[i - 1].Type == TT_ObjCMethodSpecifier)
976 return true;
977 if (Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
978 Current.Tok.is(tok::identifier))
979 // Don't space between ')' and <id>
980 return false;
981 if (Line.Tokens[i - 1].Tok.is(tok::colon) && Current.Tok.is(tok::l_paren))
982 // Don't space between ':' and '('
983 return false;
984 }
985
986 if (Annotation.Type == TT_CtorInitializerColon)
987 return true;
988 if (Annotation.Type == TT_OverloadedOperator)
989 return Current.Tok.is(tok::identifier) || Current.Tok.is(tok::kw_new) ||
990 Current.Tok.is(tok::kw_delete);
991 if (Annotations[i - 1].Type == TT_OverloadedOperator)
992 return false;
993 if (Current.Tok.is(tok::colon))
994 return Line.Tokens[0].Tok.isNot(tok::kw_case) &&
995 (i != Line.Tokens.size() - 1);
996 if (Annotations[i - 1].Type == TT_UnaryOperator)
997 return false;
998 if (Annotation.Type == TT_UnaryOperator)
999 return Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
1000 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
1001 if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
1002 Current.Tok.is(tok::greater)) {
1003 return Annotation.Type == TT_TemplateCloser && Annotations[i - 1].Type ==
1004 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1005 }
1006 if (Annotation.Type == TT_DirectorySeparator ||
1007 Annotations[i - 1].Type == TT_DirectorySeparator)
1008 return false;
1009 if (Annotation.Type == TT_BinaryOperator ||
1010 Annotations[i - 1].Type == TT_BinaryOperator)
1011 return true;
1012 if (Annotations[i - 1].Type == TT_TemplateCloser &&
1013 Current.Tok.is(tok::l_paren))
1014 return false;
1015 if (Current.Tok.is(tok::less) && Line.Tokens[0].Tok.is(tok::hash))
1016 return true;
1017 if (Annotation.Type == TT_TrailingUnaryOperator)
1018 return false;
1019 return spaceRequiredBetween(Line.Tokens[i - 1].Tok, Current.Tok);
1020 }
1021
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001022 bool canBreakBefore(unsigned i) {
Daniel Jasperda927712013-01-07 15:36:15 +00001023 if (CurrentLineType == LT_ObjCMethodDecl) {
1024 if (Line.Tokens[i].Tok.is(tok::identifier) &&
1025 (i != Line.Tokens.size() - 1) &&
1026 Line.Tokens[i + 1].Tok.is(tok::colon) &&
1027 Line.Tokens[i - 1].Tok.is(tok::identifier))
1028 return true;
1029 if (CurrentLineType == LT_ObjCMethodDecl &&
1030 Line.Tokens[i].Tok.is(tok::identifier) &&
1031 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
1032 Line.Tokens[i - 2].Tok.is(tok::colon))
1033 // Don't break this identifier as ':' or identifier
1034 // before it will break.
1035 return false;
1036 if (Line.Tokens[i].Tok.is(tok::colon) &&
1037 Line.Tokens[i - 1].Tok.is(tok::identifier) &&
1038 Annotations[i - 1].CanBreakBefore)
1039 // Don't break at ':' if identifier before it can beak.
1040 return false;
1041 }
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001042 if (Annotations[i - 1].ClosesTemplateDeclaration)
1043 return true;
Daniel Jasper71607512013-01-07 10:48:50 +00001044 if (Annotations[i - 1].Type == TT_PointerOrReference ||
1045 Annotations[i - 1].Type == TT_TemplateCloser ||
1046 Annotations[i].Type == TT_ConditionalExpr) {
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001047 return false;
1048 }
1049 const FormatToken &Left = Line.Tokens[i - 1];
1050 const FormatToken &Right = Line.Tokens[i];
Daniel Jasper71607512013-01-07 10:48:50 +00001051 if (Left.Tok.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
1052 return false;
1053
Daniel Jasper05b1ac82012-12-17 11:29:41 +00001054 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
1055 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001056 return false;
Daniel Jasper675d2e32012-12-21 10:20:02 +00001057 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001058 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
1059 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
1060 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
1061 Left.Tok.is(tok::l_brace) ||
1062 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001063 }
1064
1065 const UnwrappedLine &Line;
1066 FormatStyle Style;
1067 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001068 Lexer &Lex;
Daniel Jasper71607512013-01-07 10:48:50 +00001069 LineType CurrentLineType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001070 std::vector<TokenAnnotation> Annotations;
1071};
1072
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001073class LexerBasedFormatTokenSource : public FormatTokenSource {
1074public:
1075 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001076 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001077 IdentTable(Lex.getLangOpts()) {
1078 Lex.SetKeepWhitespaceMode(true);
1079 }
1080
1081 virtual FormatToken getNextToken() {
1082 if (GreaterStashed) {
1083 FormatTok.NewlinesBefore = 0;
1084 FormatTok.WhiteSpaceStart =
1085 FormatTok.Tok.getLocation().getLocWithOffset(1);
1086 FormatTok.WhiteSpaceLength = 0;
1087 GreaterStashed = false;
1088 return FormatTok;
1089 }
1090
1091 FormatTok = FormatToken();
1092 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001093 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001094 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001095 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1096 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001097
1098 // Consume and record whitespace until we find a significant token.
1099 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001100 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001101 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1102 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001103 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1104
1105 if (FormatTok.Tok.is(tok::eof))
1106 return FormatTok;
1107 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001108 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001109 }
Manuel Klimek95419382013-01-07 07:56:50 +00001110
1111 // Now FormatTok is the next non-whitespace token.
1112 FormatTok.TokenLength = Text.size();
1113
Manuel Klimekd4397b92013-01-04 23:34:14 +00001114 // In case the token starts with escaped newlines, we want to
1115 // take them into account as whitespace - this pattern is quite frequent
1116 // in macro definitions.
1117 // FIXME: What do we want to do with other escaped spaces, and escaped
1118 // spaces or newlines in the middle of tokens?
1119 // FIXME: Add a more explicit test.
1120 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001121 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001122 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001123 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001124 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001125 }
1126
1127 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001128 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001129 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001130 FormatTok.Tok.setKind(Info.getTokenID());
1131 }
1132
1133 if (FormatTok.Tok.is(tok::greatergreater)) {
1134 FormatTok.Tok.setKind(tok::greater);
1135 GreaterStashed = true;
1136 }
1137
1138 return FormatTok;
1139 }
1140
1141private:
1142 FormatToken FormatTok;
1143 bool GreaterStashed;
1144 Lexer &Lex;
1145 SourceManager &SourceMgr;
1146 IdentifierTable IdentTable;
1147
1148 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001149 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001150 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1151 Tok.getLength());
1152 }
1153};
1154
Daniel Jasperbac016b2012-12-03 18:12:45 +00001155class Formatter : public UnwrappedLineConsumer {
1156public:
1157 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1158 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001159 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001160 StructuralError(false) {
Daniel Jasperbac016b2012-12-03 18:12:45 +00001161 }
1162
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001163 virtual ~Formatter() {
1164 }
1165
Daniel Jasperbac016b2012-12-03 18:12:45 +00001166 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001167 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1168 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001169 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001170 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001171 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1172 E = UnwrappedLines.end();
1173 I != E; ++I)
Daniel Jaspercd162382013-01-07 13:26:07 +00001174 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1175 PreviousEndOfLineColumn);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001176 return Replaces;
1177 }
1178
1179private:
Alexander Kornienko720ffb62012-12-05 13:56:52 +00001180 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001181 UnwrappedLines.push_back(TheLine);
1182 }
1183
Manuel Klimekd4397b92013-01-04 23:34:14 +00001184 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1185 unsigned PreviousEndOfLineColumn) {
1186 if (TheLine.Tokens.empty())
Daniel Jaspercd162382013-01-07 13:26:07 +00001187 return 0; // FIXME: Find out how this can ever happen.
Daniel Jasperbac016b2012-12-03 18:12:45 +00001188
Daniel Jaspercd162382013-01-07 13:26:07 +00001189 CharSourceRange LineRange = CharSourceRange::getTokenRange(
1190 TheLine.Tokens.front().Tok.getLocation(),
1191 TheLine.Tokens.back().Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001192
1193 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1194 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1195 Ranges[i].getBegin()) ||
1196 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1197 LineRange.getBegin()))
1198 continue;
1199
Manuel Klimek6cf58142013-01-07 08:54:53 +00001200 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasper1f42f112013-01-04 18:52:56 +00001201 if (!Annotator.annotate())
Manuel Klimekd4397b92013-01-04 23:34:14 +00001202 break;
1203 UnwrappedLineFormatter Formatter(
1204 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
Daniel Jasper71607512013-01-07 10:48:50 +00001205 Annotator.getLineType(), Annotator.getAnnotations(), Replaces,
1206 StructuralError);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001207 return Formatter.format();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001208 }
Manuel Klimekd4397b92013-01-04 23:34:14 +00001209 // If we did not reformat this unwrapped line, the column at the end of the
1210 // last token is unchanged - thus, we can calculate the end of the last
1211 // token, and return the result.
1212 const FormatToken &Token = TheLine.Tokens.back();
1213 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) +
1214 Lex.MeasureTokenLength(Token.Tok.getLocation(), SourceMgr,
1215 Lex.getLangOpts()) -
1216 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001217 }
1218
1219 FormatStyle Style;
1220 Lexer &Lex;
1221 SourceManager &SourceMgr;
1222 tooling::Replacements Replaces;
1223 std::vector<CharSourceRange> Ranges;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001224 std::vector<UnwrappedLine> UnwrappedLines;
1225 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001226};
1227
1228tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1229 SourceManager &SourceMgr,
1230 std::vector<CharSourceRange> Ranges) {
1231 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1232 return formatter.format();
1233}
1234
Daniel Jaspercd162382013-01-07 13:26:07 +00001235} // namespace format
1236} // namespace clang