blob: 3dbf95c5a40539d3b8d790baea8eefdce56eae9c [file] [log] [blame]
Daniel Jasperf7935112012-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 Carruth3a022472012-12-04 09:13:33 +000020#include "UnwrappedLineParser.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000021#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000022#include "clang/Basic/SourceManager.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000023#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000024#include <string>
25
Daniel Jasperf7935112012-12-03 18:12:45 +000026namespace clang {
27namespace format {
28
Daniel Jasperda16db32013-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 Jasperf7935112012-12-03 18:12:45 +000055// FIXME: Move somewhere sane.
56struct TokenAnnotation {
Daniel Jasperf7935112012-12-03 18:12:45 +000057 TokenType Type;
58
Daniel Jasperf7935112012-12-03 18:12:45 +000059 bool SpaceRequiredBefore;
60 bool CanBreakBefore;
61 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000062
63 bool ClosesTemplateDeclaration;
Daniel Jasperf7935112012-12-03 18:12:45 +000064};
65
Daniel Jasper2eda23e2012-12-24 13:43:52 +000066static prec::Level getPrecedence(const FormatToken &Tok) {
67 return getBinOpPrecedence(Tok.Tok.getKind(), true, true);
68}
69
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +000079 LLVMStyle.IndentCaseLabels = false;
Daniel Jasperf7935112012-12-03 18:12:45 +000080 return LLVMStyle;
81}
82
83FormatStyle getGoogleStyle() {
84 FormatStyle GoogleStyle;
85 GoogleStyle.ColumnLimit = 80;
86 GoogleStyle.MaxEmptyLinesToKeep = 1;
87 GoogleStyle.PointerAndReferenceBindToType = true;
88 GoogleStyle.AccessModifierOffset = -1;
89 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +000090 GoogleStyle.IndentCaseLabels = true;
Daniel Jasperf7935112012-12-03 18:12:45 +000091 return GoogleStyle;
92}
93
94struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +000095 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +000096 unsigned PenaltyLevelDecrease;
Daniel Jasperf7935112012-12-03 18:12:45 +000097};
98
99class UnwrappedLineFormatter {
100public:
101 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
102 const UnwrappedLine &Line,
Manuel Klimek1abf7892013-01-04 23:34:14 +0000103 unsigned PreviousEndOfLineColumn,
Daniel Jasperda16db32013-01-07 10:48:50 +0000104 LineType CurrentLineType,
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 const std::vector<TokenAnnotation> &Annotations,
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000106 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000107 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimek1abf7892013-01-04 23:34:14 +0000108 PreviousEndOfLineColumn(PreviousEndOfLineColumn),
Daniel Jasperda16db32013-01-07 10:48:50 +0000109 CurrentLineType(CurrentLineType), Annotations(Annotations),
110 Replaces(Replaces), StructuralError(StructuralError) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000111 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000112 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperf7935112012-12-03 18:12:45 +0000113 }
114
Manuel Klimek1abf7892013-01-04 23:34:14 +0000115 /// \brief Formats an \c UnwrappedLine.
116 ///
117 /// \returns The column after the last token in the last line of the
118 /// \c UnwrappedLine.
119 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000120 // Format first token and initialize indent.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000121 unsigned Indent = formatFirstToken();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000122
123 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000124 IndentState State;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000125 State.Column = Indent;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000126 State.ConsumedTokens = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000127 State.Indent.push_back(Indent + 4);
128 State.LastSpace.push_back(Indent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000129 State.FirstLessLess.push_back(0);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000130 State.ForLoopVariablePos = 0;
131 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000132 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000133
134 // The first token has already been indented and thus consumed.
135 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000136
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000137 // Check whether the UnwrappedLine can be put onto a single line. If so,
138 // this is bound to be the optimal solution (by definition) and we don't
Daniel Jasperc0880a92013-01-04 18:52:56 +0000139 // need to analyze the entire solution space.
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000140 unsigned Columns = State.Column;
141 bool FitsOnALine = true;
142 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
143 Columns += (Annotations[i].SpaceRequiredBefore ? 1 : 0) +
Manuel Klimekef920692013-01-07 07:56:50 +0000144 Line.Tokens[i].TokenLength;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000145 // A special case for the colon of a constructor initializer as this only
146 // needs to be put on a new line if the line needs to be split.
Manuel Klimek38ba11e2013-01-07 09:24:17 +0000147 if (Columns > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0) ||
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000148 (Annotations[i].MustBreakBefore &&
Daniel Jasperda16db32013-01-07 10:48:50 +0000149 Annotations[i].Type != TT_CtorInitializerColon)) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000150 FitsOnALine = false;
151 break;
152 }
153 }
154
Daniel Jasperf7935112012-12-03 18:12:45 +0000155 // Start iterating at 1 as we have correctly formatted of Token #0 above.
156 for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000157 if (FitsOnALine) {
158 addTokenToState(false, false, State);
159 } else {
160 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
161 unsigned Break = calcPenalty(State, true, NoBreak);
162 addTokenToState(Break < NoBreak, false, State);
163 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000164 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000165 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000166 }
167
168private:
169 /// \brief The current state when indenting a unwrapped line.
170 ///
171 /// As the indenting tries different combinations this is copied by value.
172 struct IndentState {
173 /// \brief The number of used columns in the current line.
174 unsigned Column;
175
176 /// \brief The number of tokens already consumed.
177 unsigned ConsumedTokens;
178
Daniel Jasper6d822722012-12-24 16:43:00 +0000179 /// \brief The parenthesis level of the first token on the current line.
180 unsigned StartOfLineLevel;
181
Daniel Jasperf7935112012-12-03 18:12:45 +0000182 /// \brief The position to which a specific parenthesis level needs to be
183 /// indented.
184 std::vector<unsigned> Indent;
185
Daniel Jaspere9de2602012-12-06 09:56:08 +0000186 /// \brief The position of the last space on each level.
187 ///
188 /// Used e.g. to break like:
189 /// functionCall(Parameter, otherCall(
190 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000191 std::vector<unsigned> LastSpace;
192
Daniel Jaspere9de2602012-12-06 09:56:08 +0000193 /// \brief The position the first "<<" operator encountered on each level.
194 ///
195 /// Used to align "<<" operators. 0 if no such operator has been encountered
196 /// on a level.
197 std::vector<unsigned> FirstLessLess;
198
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000199 /// \brief The column of the first variable in a for-loop declaration.
200 ///
201 /// Used to align the second variable if necessary.
202 unsigned ForLoopVariablePos;
203
204 /// \brief \c true if this line contains a continued for-loop section.
205 bool LineContainsContinuedForLoopSection;
206
Daniel Jasperf7935112012-12-03 18:12:45 +0000207 /// \brief Comparison operator to be able to used \c IndentState in \c map.
208 bool operator<(const IndentState &Other) const {
209 if (Other.ConsumedTokens != ConsumedTokens)
210 return Other.ConsumedTokens > ConsumedTokens;
211 if (Other.Column != Column)
212 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000213 if (Other.StartOfLineLevel != StartOfLineLevel)
214 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000215 if (Other.Indent.size() != Indent.size())
216 return Other.Indent.size() > Indent.size();
217 for (int i = 0, e = Indent.size(); i != e; ++i) {
218 if (Other.Indent[i] != Indent[i])
219 return Other.Indent[i] > Indent[i];
220 }
221 if (Other.LastSpace.size() != LastSpace.size())
222 return Other.LastSpace.size() > LastSpace.size();
223 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
224 if (Other.LastSpace[i] != LastSpace[i])
225 return Other.LastSpace[i] > LastSpace[i];
226 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000227 if (Other.FirstLessLess.size() != FirstLessLess.size())
228 return Other.FirstLessLess.size() > FirstLessLess.size();
229 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
230 if (Other.FirstLessLess[i] != FirstLessLess[i])
231 return Other.FirstLessLess[i] > FirstLessLess[i];
232 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000233 if (Other.ForLoopVariablePos != ForLoopVariablePos)
234 return Other.ForLoopVariablePos < ForLoopVariablePos;
235 if (Other.LineContainsContinuedForLoopSection !=
236 LineContainsContinuedForLoopSection)
237 return LineContainsContinuedForLoopSection;
Daniel Jasperf7935112012-12-03 18:12:45 +0000238 return false;
239 }
240 };
241
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000242 /// \brief Appends the next token to \p State and updates information
243 /// necessary for indentation.
244 ///
245 /// Puts the token on the current line if \p Newline is \c true and adds a
246 /// line break and necessary indentation otherwise.
247 ///
248 /// If \p DryRun is \c false, also creates and stores the required
249 /// \c Replacement.
250 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000251 unsigned Index = State.ConsumedTokens;
252 const FormatToken &Current = Line.Tokens[Index];
253 const FormatToken &Previous = Line.Tokens[Index - 1];
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000254 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000255
256 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000257 unsigned WhitespaceStartColumn = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000258 if (Current.Tok.is(tok::string_literal) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000259 Previous.Tok.is(tok::string_literal)) {
Manuel Klimekef920692013-01-07 07:56:50 +0000260 State.Column = State.Column - Previous.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000261 } else if (Current.Tok.is(tok::lessless) &&
262 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000263 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000264 } else if (ParenLevel != 0 &&
265 (Previous.Tok.is(tok::equal) || Current.Tok.is(tok::arrow) ||
266 Current.Tok.is(tok::period))) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000267 // Indent and extra 4 spaces after '=' as it continues an expression.
268 // Don't do that on the top level, as we already indent 4 there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000269 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasperda16db32013-01-07 10:48:50 +0000270 } else if (Line.Tokens[0].Tok.is(tok::kw_for) &&
271 Previous.Tok.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000272 State.Column = State.ForLoopVariablePos;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000273 } else if (Annotations[Index - 1].ClosesTemplateDeclaration) {
274 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000275 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000276 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000277 }
278
Daniel Jasper6d822722012-12-24 16:43:00 +0000279 State.StartOfLineLevel = ParenLevel + 1;
280
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000281 if (Line.Tokens[0].Tok.is(tok::kw_for))
282 State.LineContainsContinuedForLoopSection =
283 Previous.Tok.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000284
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000285 if (!DryRun) {
286 if (!Line.InPPDirective)
287 replaceWhitespace(Current, 1, State.Column);
288 else
289 replacePPWhitespace(Current, 1, State.Column, WhitespaceStartColumn);
290 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000291
Daniel Jasper9b155472012-12-04 10:50:12 +0000292 State.LastSpace[ParenLevel] = State.Indent[ParenLevel];
Daniel Jasperda16db32013-01-07 10:48:50 +0000293 if (Current.Tok.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
294 Annotations[Index].Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000295 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000296 } else {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000297 if (Current.Tok.is(tok::equal) && Line.Tokens[0].Tok.is(tok::kw_for))
Manuel Klimekef920692013-01-07 07:56:50 +0000298 State.ForLoopVariablePos = State.Column - Previous.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000299
Daniel Jasperf7935112012-12-03 18:12:45 +0000300 unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0;
Daniel Jasperda16db32013-01-07 10:48:50 +0000301 if (Annotations[Index].Type == TT_LineComment)
Daniel Jasperf7935112012-12-03 18:12:45 +0000302 Spaces = 2;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000303
Daniel Jasperf7935112012-12-03 18:12:45 +0000304 if (!DryRun)
305 replaceWhitespace(Current, 0, Spaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000306
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000307 // FIXME: Look into using this alignment at other ParenLevels.
308 if (ParenLevel == 0 && (getPrecedence(Previous) == prec::Assignment ||
309 Previous.Tok.is(tok::kw_return)))
310 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000311 if (Previous.Tok.is(tok::l_paren) ||
Daniel Jasperda16db32013-01-07 10:48:50 +0000312 Annotations[Index - 1].Type == TT_TemplateOpener)
Daniel Jasperf7935112012-12-03 18:12:45 +0000313 State.Indent[ParenLevel] = State.Column;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000314
Daniel Jasperf7935112012-12-03 18:12:45 +0000315 // Top-level spaces are exempt as that mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000316 State.Column += Spaces;
Daniel Jasper9b155472012-12-04 10:50:12 +0000317 if (Spaces > 0 && ParenLevel != 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000318 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000319 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000320 moveStateToNextToken(State);
321 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000322
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000323 /// \brief Mark the next token as consumed in \p State and modify its stacks
324 /// accordingly.
325 void moveStateToNextToken(IndentState &State) {
326 unsigned Index = State.ConsumedTokens;
327 const FormatToken &Current = Line.Tokens[Index];
Daniel Jaspere9de2602012-12-06 09:56:08 +0000328 unsigned ParenLevel = State.Indent.size() - 1;
329
330 if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
331 State.FirstLessLess[ParenLevel] = State.Column;
332
Manuel Klimekef920692013-01-07 07:56:50 +0000333 State.Column += Current.TokenLength;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000334
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000335 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000336 // prepare for the following tokens.
337 if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000338 Current.Tok.is(tok::l_brace) ||
Daniel Jasperda16db32013-01-07 10:48:50 +0000339 Annotations[Index].Type == TT_TemplateOpener) {
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000340 State.Indent.push_back(4 + State.LastSpace.back());
341 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000342 State.FirstLessLess.push_back(0);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000343 }
344
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000345 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000346 // stacks.
Daniel Jasper9b155472012-12-04 10:50:12 +0000347 if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) ||
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000348 (Current.Tok.is(tok::r_brace) && State.ConsumedTokens > 0) ||
Daniel Jasperda16db32013-01-07 10:48:50 +0000349 Annotations[Index].Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 State.Indent.pop_back();
351 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000352 State.FirstLessLess.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 }
354
355 ++State.ConsumedTokens;
356 }
357
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000358 /// \brief Calculate the panelty for splitting after the token at \p Index.
359 unsigned splitPenalty(unsigned Index) {
360 assert(Index < Line.Tokens.size() &&
361 "Tried to calculate penalty for splitting after the last token");
362 const FormatToken &Left = Line.Tokens[Index];
363 const FormatToken &Right = Line.Tokens[Index + 1];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000364
365 // In for-loops, prefer breaking at ',' and ';'.
366 if (Line.Tokens[0].Tok.is(tok::kw_for) &&
367 (Left.Tok.isNot(tok::comma) && Left.Tok.isNot(tok::semi)))
368 return 20;
369
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000370 if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma) ||
371 Annotations[Index].ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000372 return 0;
Daniel Jasperde5c2072012-12-24 00:13:23 +0000373 if (Left.Tok.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000374 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000375
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000376 prec::Level Level = getPrecedence(Line.Tokens[Index]);
Daniel Jasperde5c2072012-12-24 00:13:23 +0000377 if (Level != prec::Unknown)
378 return Level;
379
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000380 if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000381 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000382
Daniel Jasperf7935112012-12-03 18:12:45 +0000383 return 3;
384 }
385
386 /// \brief Calculate the number of lines needed to format the remaining part
387 /// of the unwrapped line.
388 ///
389 /// Assumes the formatting so far has led to
390 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
391 /// added after the previous token.
392 ///
393 /// \param StopAt is used for optimization. If we can determine that we'll
394 /// definitely need at least \p StopAt additional lines, we already know of a
395 /// better solution.
396 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
397 // We are at the end of the unwrapped line, so we don't need any more lines.
398 if (State.ConsumedTokens >= Line.Tokens.size())
399 return 0;
400
401 if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore)
402 return UINT_MAX;
403 if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore)
404 return UINT_MAX;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000405 if (!NewLine && Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::semi) &&
406 State.LineContainsContinuedForLoopSection)
407 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000408
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000409 unsigned CurrentPenalty = 0;
410 if (NewLine) {
411 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000412 splitPenalty(State.ConsumedTokens - 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000413 } else {
414 if (State.Indent.size() < State.StartOfLineLevel)
415 CurrentPenalty += Parameters.PenaltyLevelDecrease *
416 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000417 }
418
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000419 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000420
421 // Exceeding column limit is bad.
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000422 if (State.Column > Style.ColumnLimit - (Line.InPPDirective ? 1 : 0))
Daniel Jasperf7935112012-12-03 18:12:45 +0000423 return UINT_MAX;
424
Daniel Jasperf7935112012-12-03 18:12:45 +0000425 if (StopAt <= CurrentPenalty)
426 return UINT_MAX;
427 StopAt -= CurrentPenalty;
428
Daniel Jasperf7935112012-12-03 18:12:45 +0000429 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000430 if (I != Memory.end()) {
431 // If this state has already been examined, we can safely return the
432 // previous result if we
433 // - have not hit the optimatization (and thus returned UINT_MAX) OR
434 // - are now computing for a smaller or equal StopAt.
435 unsigned SavedResult = I->second.first;
436 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000437 if (SavedResult != UINT_MAX)
438 return SavedResult + CurrentPenalty;
439 else if (StopAt <= SavedStopAt)
440 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000441 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000442
443 unsigned NoBreak = calcPenalty(State, false, StopAt);
444 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
445 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000446
447 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
448 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000449 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000450
451 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000452 }
453
454 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
455 /// each \c FormatToken.
456 void replaceWhitespace(const FormatToken &Tok, unsigned NewLines,
457 unsigned Spaces) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000458 Replaces.insert(tooling::Replacement(
459 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
460 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
461 }
462
463 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
464 /// backslashes to escape newlines inside a preprocessor directive.
465 ///
466 /// This function and \c replaceWhitespace have the same behavior if
467 /// \c Newlines == 0.
468 void replacePPWhitespace(const FormatToken &Tok, unsigned NewLines,
469 unsigned Spaces, unsigned WhitespaceStartColumn) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000470 std::string NewLineText;
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000471 if (NewLines > 0) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000472 unsigned Offset =
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000473 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000474 for (unsigned i = 0; i < NewLines; ++i) {
475 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
476 NewLineText += "\\\n";
477 Offset = 0;
478 }
479 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000480 Replaces.insert(tooling::Replacement(
481 SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength,
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000482 NewLineText + std::string(Spaces, ' ')));
Daniel Jasperf7935112012-12-03 18:12:45 +0000483 }
484
485 /// \brief Add a new line and the required indent before the first Token
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +0000486 /// of the \c UnwrappedLine if there was no structural parsing error.
487 /// Returns the indent level of the \c UnwrappedLine.
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000488 unsigned formatFirstToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000489 const FormatToken &Token = Line.Tokens[0];
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000490 if (!Token.WhiteSpaceStart.isValid() || StructuralError)
491 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1;
492
493 unsigned Newlines =
494 std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000495 if (Newlines == 0 && !Token.IsFirst)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000496 Newlines = 1;
497 unsigned Indent = Line.Level * 2;
Alexander Kornienko2ca766f2012-12-10 16:34:48 +0000498 if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) ||
499 Token.Tok.is(tok::kw_private)) &&
500 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000501 Indent += Style.AccessModifierOffset;
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000502 if (!Line.InPPDirective || Token.HasUnescapedNewline)
503 replaceWhitespace(Token, Newlines, Indent);
504 else
Manuel Klimek1abf7892013-01-04 23:34:14 +0000505 replacePPWhitespace(Token, Newlines, Indent, PreviousEndOfLineColumn);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000506 return Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000507 }
508
509 FormatStyle Style;
510 SourceManager &SourceMgr;
511 const UnwrappedLine &Line;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000512 const unsigned PreviousEndOfLineColumn;
Daniel Jasperda16db32013-01-07 10:48:50 +0000513 const LineType CurrentLineType;
Daniel Jasperf7935112012-12-03 18:12:45 +0000514 const std::vector<TokenAnnotation> &Annotations;
515 tooling::Replacements &Replaces;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +0000516 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +0000517
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000518 // A map from an indent state to a pair (Result, Used-StopAt).
519 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
520 StateMap Memory;
521
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 OptimizationParameters Parameters;
523};
524
525/// \brief Determines extra information about the tokens comprising an
526/// \c UnwrappedLine.
527class TokenAnnotator {
528public:
529 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000530 SourceManager &SourceMgr, Lexer &Lex)
531 : Line(Line), Style(Style), SourceMgr(SourceMgr), Lex(Lex) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000532 }
533
534 /// \brief A parser that gathers additional information about tokens.
535 ///
536 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
537 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
538 /// into template parameter lists.
539 class AnnotatingParser {
540 public:
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000541 AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +0000542 std::vector<TokenAnnotation> &Annotations)
Daniel Jasperda16db32013-01-07 10:48:50 +0000543 : Tokens(Tokens), Annotations(Annotations), Index(0),
544 KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000545 }
546
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000547 bool parseAngle() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000548 while (Index < Tokens.size()) {
549 if (Tokens[Index].Tok.is(tok::greater)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000550 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000551 next();
552 return true;
553 }
554 if (Tokens[Index].Tok.is(tok::r_paren) ||
Daniel Jasperc0880a92013-01-04 18:52:56 +0000555 Tokens[Index].Tok.is(tok::r_square) ||
556 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 return false;
558 if (Tokens[Index].Tok.is(tok::pipepipe) ||
559 Tokens[Index].Tok.is(tok::ampamp) ||
560 Tokens[Index].Tok.is(tok::question) ||
561 Tokens[Index].Tok.is(tok::colon))
562 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000563 if (!consumeToken())
564 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000565 }
566 return false;
567 }
568
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000569 bool parseParens() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 while (Index < Tokens.size()) {
571 if (Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000572 next();
573 return true;
574 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000575 if (Tokens[Index].Tok.is(tok::r_square) ||
576 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000578 if (!consumeToken())
579 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000580 }
581 return false;
582 }
583
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000584 bool parseSquare() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 while (Index < Tokens.size()) {
586 if (Tokens[Index].Tok.is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000587 next();
588 return true;
589 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000590 if (Tokens[Index].Tok.is(tok::r_paren) ||
591 Tokens[Index].Tok.is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000593 if (!consumeToken())
594 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 }
596 return false;
597 }
598
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599 bool parseConditional() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 while (Index < Tokens.size()) {
601 if (Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000602 Annotations[Index].Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000603 next();
604 return true;
605 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000606 if (!consumeToken())
607 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000608 }
609 return false;
610 }
611
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000612 bool parseTemplateDeclaration() {
613 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::less)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000614 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000615 next();
616 if (!parseAngle())
617 return false;
618 Annotations[Index - 1].ClosesTemplateDeclaration = true;
619 parseLine();
620 return true;
621 }
622 return false;
623 }
624
Daniel Jasperc0880a92013-01-04 18:52:56 +0000625 bool consumeToken() {
Daniel Jasperf7935112012-12-03 18:12:45 +0000626 unsigned CurrentIndex = Index;
627 next();
628 switch (Tokens[CurrentIndex].Tok.getKind()) {
629 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000630 if (!parseParens())
631 return false;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000632 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::colon)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000633 Annotations[Index].Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000634 next();
635 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000636 break;
637 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000638 if (!parseSquare())
639 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000640 break;
641 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000642 if (parseAngle())
Daniel Jasperda16db32013-01-07 10:48:50 +0000643 Annotations[CurrentIndex].Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000644 else {
Daniel Jasperda16db32013-01-07 10:48:50 +0000645 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 Index = CurrentIndex + 1;
647 }
648 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000649 case tok::r_paren:
650 case tok::r_square:
651 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 case tok::greater:
Daniel Jasperda16db32013-01-07 10:48:50 +0000653 Annotations[CurrentIndex].Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000654 break;
655 case tok::kw_operator:
Daniel Jasper537a2962012-12-24 10:56:04 +0000656 if (Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000657 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000658 next();
659 if (Index < Tokens.size() && Tokens[Index].Tok.is(tok::r_paren)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000660 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000661 next();
662 }
663 } else {
664 while (Index < Tokens.size() && !Tokens[Index].Tok.is(tok::l_paren)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000665 Annotations[Index].Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000666 next();
667 }
668 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 break;
670 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000671 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000672 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000673 case tok::kw_template:
674 parseTemplateDeclaration();
675 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000676 default:
677 break;
678 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000679 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000680 }
681
Daniel Jasper050948a52012-12-21 17:58:39 +0000682 void parseIncludeDirective() {
683 while (Index < Tokens.size()) {
684 if (Tokens[Index].Tok.is(tok::slash))
Daniel Jasperda16db32013-01-07 10:48:50 +0000685 Annotations[Index].Type = TT_DirectorySeparator;
Daniel Jasper050948a52012-12-21 17:58:39 +0000686 else if (Tokens[Index].Tok.is(tok::less))
Daniel Jasperda16db32013-01-07 10:48:50 +0000687 Annotations[Index].Type = TT_TemplateOpener;
Daniel Jasper050948a52012-12-21 17:58:39 +0000688 else if (Tokens[Index].Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000689 Annotations[Index].Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000690 next();
691 }
692 }
693
694 void parsePreprocessorDirective() {
695 next();
696 if (Index >= Tokens.size())
697 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000698 // Hashes in the middle of a line can lead to any strange token
699 // sequence.
700 if (Tokens[Index].Tok.getIdentifierInfo() == NULL)
701 return;
Daniel Jasper050948a52012-12-21 17:58:39 +0000702 switch (Tokens[Index].Tok.getIdentifierInfo()->getPPKeywordID()) {
703 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000704 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000705 parseIncludeDirective();
706 break;
707 default:
708 break;
709 }
710 }
711
Daniel Jasperda16db32013-01-07 10:48:50 +0000712 LineType parseLine() {
Daniel Jasper050948a52012-12-21 17:58:39 +0000713 if (Tokens[Index].Tok.is(tok::hash)) {
714 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000715 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000716 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 while (Index < Tokens.size()) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000718 if (Tokens[Index].Tok.is(tok::kw_virtual))
719 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000720 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000721 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000723 if (KeywordVirtualFound)
724 return LT_VirtualFunctionDecl;
725 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000726 }
727
728 void next() {
729 ++Index;
730 }
731
732 private:
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 const SmallVector<FormatToken, 16> &Tokens;
734 std::vector<TokenAnnotation> &Annotations;
735 unsigned Index;
Daniel Jasperda16db32013-01-07 10:48:50 +0000736 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 };
738
Daniel Jasperc0880a92013-01-04 18:52:56 +0000739 bool annotate() {
Daniel Jasperda16db32013-01-07 10:48:50 +0000740 if (Line.Tokens.size() == 0)
741 return true;
742
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 Annotations.clear();
744 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
745 Annotations.push_back(TokenAnnotation());
746 }
747
Manuel Klimek6a5619d2012-12-03 20:55:42 +0000748 AnnotatingParser Parser(Line.Tokens, Annotations);
Daniel Jasperda16db32013-01-07 10:48:50 +0000749 CurrentLineType = Parser.parseLine();
750 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000751 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000752
753 determineTokenTypes();
Daniel Jasperda16db32013-01-07 10:48:50 +0000754
755 if (Annotations[0].Type == TT_ObjCMethodSpecifier)
756 CurrentLineType = LT_ObjCMethodDecl;
757
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 for (int i = 1, e = Line.Tokens.size(); i != e; ++i) {
759 TokenAnnotation &Annotation = Annotations[i];
760
Daniel Jasperd1926a32013-01-02 08:44:14 +0000761 Annotation.CanBreakBefore = canBreakBefore(i);
Daniel Jasperf7935112012-12-03 18:12:45 +0000762
Daniel Jasperda16db32013-01-07 10:48:50 +0000763 if (Annotation.Type == TT_CtorInitializerColon) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000764 Annotation.MustBreakBefore = true;
765 Annotation.SpaceRequiredBefore = true;
Daniel Jasperda16db32013-01-07 10:48:50 +0000766 } else if (Annotation.Type == TT_OverloadedOperator) {
Daniel Jasper537a2962012-12-24 10:56:04 +0000767 Annotation.SpaceRequiredBefore =
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000768 Line.Tokens[i].Tok.is(tok::identifier) ||
769 Line.Tokens[i].Tok.is(tok::kw_new) ||
770 Line.Tokens[i].Tok.is(tok::kw_delete);
Daniel Jasperda16db32013-01-07 10:48:50 +0000771 } else if (Annotations[i - 1].Type == TT_OverloadedOperator) {
Daniel Jasper537a2962012-12-24 10:56:04 +0000772 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000773 } else if (CurrentLineType == LT_ObjCMethodDecl &&
774 Line.Tokens[i].Tok.is(tok::identifier) && (i != e - 1) &&
775 Line.Tokens[i + 1].Tok.is(tok::colon) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000776 Line.Tokens[i - 1].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000777 Annotation.CanBreakBefore = true;
778 Annotation.SpaceRequiredBefore = true;
Daniel Jasperda16db32013-01-07 10:48:50 +0000779 } else if (CurrentLineType == LT_ObjCMethodDecl &&
780 Line.Tokens[i].Tok.is(tok::identifier) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000781 Line.Tokens[i - 1].Tok.is(tok::l_paren) &&
782 Line.Tokens[i - 2].Tok.is(tok::colon)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000783 // Don't break this identifier as ':' or identifier
784 // before it will break.
785 Annotation.CanBreakBefore = false;
786 } else if (Line.Tokens[i].Tok.is(tok::at) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000787 Line.Tokens[i - 2].Tok.is(tok::at)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000788 // Don't put two objc's '@' on the same line. This could happen,
Fariborz Jahanian3b1604e2012-12-21 17:14:23 +0000789 // as in, @optional @property ...
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000790 Annotation.MustBreakBefore = true;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000791 } else if (Line.Tokens[i].Tok.is(tok::colon)) {
Daniel Jasper55b6b642012-12-05 16:24:48 +0000792 Annotation.SpaceRequiredBefore =
Daniel Jasperda16db32013-01-07 10:48:50 +0000793 Line.Tokens[0].Tok.isNot(tok::kw_case) &&
794 CurrentLineType != LT_ObjCMethodDecl && (i != e - 1);
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000795 // Don't break at ':' if identifier before it can beak.
Daniel Jasperda16db32013-01-07 10:48:50 +0000796 if (CurrentLineType == LT_ObjCMethodDecl &&
797 Line.Tokens[i - 1].Tok.is(tok::identifier) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000798 Annotations[i - 1].CanBreakBefore)
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000799 Annotation.CanBreakBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000800 } else if (Annotations[i - 1].Type == TT_ObjCMethodSpecifier) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000801 Annotation.SpaceRequiredBefore = true;
Daniel Jasperda16db32013-01-07 10:48:50 +0000802 } else if (Annotations[i - 1].Type == TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000804 } else if (Annotation.Type == TT_UnaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000805 Annotation.SpaceRequiredBefore =
Daniel Jasper8b529712012-12-04 13:02:32 +0000806 Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&
807 Line.Tokens[i - 1].Tok.isNot(tok::l_square);
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 } else if (Line.Tokens[i - 1].Tok.is(tok::greater) &&
809 Line.Tokens[i].Tok.is(tok::greater)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000810 if (Annotation.Type == TT_TemplateCloser &&
811 Annotations[i - 1].Type == TT_TemplateCloser)
Daniel Jasper9b155472012-12-04 10:50:12 +0000812 Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater;
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 else
814 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000815 } else if (Annotation.Type == TT_DirectorySeparator ||
816 Annotations[i - 1].Type == TT_DirectorySeparator) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000817 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000818 } else if (Annotation.Type == TT_BinaryOperator ||
819 Annotations[i - 1].Type == TT_BinaryOperator) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000820 Annotation.SpaceRequiredBefore = true;
Daniel Jasperda16db32013-01-07 10:48:50 +0000821 } else if (Annotations[i - 1].Type == TT_TemplateCloser &&
822 Line.Tokens[i].Tok.is(tok::l_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 Annotation.SpaceRequiredBefore = false;
Daniel Jasper8b529712012-12-04 13:02:32 +0000824 } else if (Line.Tokens[i].Tok.is(tok::less) &&
825 Line.Tokens[0].Tok.is(tok::hash)) {
826 Annotation.SpaceRequiredBefore = true;
Daniel Jasperda16db32013-01-07 10:48:50 +0000827 } else if (CurrentLineType == LT_ObjCMethodDecl &&
828 Line.Tokens[i - 1].Tok.is(tok::r_paren) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000829 Line.Tokens[i].Tok.is(tok::identifier)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000830 // Don't space between ')' and <id>
831 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000832 } else if (CurrentLineType == LT_ObjCMethodDecl &&
833 Line.Tokens[i - 1].Tok.is(tok::colon) &&
Daniel Jasper8dd40472012-12-21 09:41:31 +0000834 Line.Tokens[i].Tok.is(tok::l_paren)) {
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000835 // Don't space between ':' and '('
836 Annotation.SpaceRequiredBefore = false;
Daniel Jasperda16db32013-01-07 10:48:50 +0000837 } else if (Annotation.Type == TT_TrailingUnaryOperator) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000838 Annotation.SpaceRequiredBefore = false;
839 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 Annotation.SpaceRequiredBefore =
841 spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok);
842 }
843
Daniel Jasperda16db32013-01-07 10:48:50 +0000844 if (Annotations[i - 1].Type == TT_LineComment ||
Daniel Jasperf7935112012-12-03 18:12:45 +0000845 (Line.Tokens[i].Tok.is(tok::string_literal) &&
846 Line.Tokens[i - 1].Tok.is(tok::string_literal))) {
847 Annotation.MustBreakBefore = true;
848 }
849
850 if (Annotation.MustBreakBefore)
851 Annotation.CanBreakBefore = true;
852 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000853 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000854 }
855
Daniel Jasperda16db32013-01-07 10:48:50 +0000856 LineType getLineType() {
857 return CurrentLineType;
858 }
859
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 const std::vector<TokenAnnotation> &getAnnotations() {
861 return Annotations;
862 }
863
864private:
865 void determineTokenTypes() {
Nico Weber6f372e62012-12-23 01:07:46 +0000866 bool IsRHS = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000867 for (int i = 0, e = Line.Tokens.size(); i != e; ++i) {
868 TokenAnnotation &Annotation = Annotations[i];
869 const FormatToken &Tok = Line.Tokens[i];
870
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000871 if (getPrecedence(Tok) == prec::Assignment)
Nico Weber6f372e62012-12-23 01:07:46 +0000872 IsRHS = true;
873 else if (Tok.Tok.is(tok::kw_return))
874 IsRHS = true;
Daniel Jasper426702d2012-12-05 07:51:39 +0000875
Daniel Jasperda16db32013-01-07 10:48:50 +0000876 if (Annotation.Type != TT_Unknown)
Daniel Jasperab7654e2012-12-21 10:20:02 +0000877 continue;
878
Daniel Jasper8dd40472012-12-21 09:41:31 +0000879 if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) {
Nico Weber6f372e62012-12-23 01:07:46 +0000880 Annotation.Type = determineStarAmpUsage(i, IsRHS);
Daniel Jasper8dd40472012-12-21 09:41:31 +0000881 } else if (Tok.Tok.is(tok::minus) || Tok.Tok.is(tok::plus)) {
882 Annotation.Type = determinePlusMinusUsage(i);
883 } else if (Tok.Tok.is(tok::minusminus) || Tok.Tok.is(tok::plusplus)) {
884 Annotation.Type = determineIncrementUsage(i);
885 } else if (Tok.Tok.is(tok::exclaim)) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000886 Annotation.Type = TT_UnaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000887 } else if (isBinaryOperator(Line.Tokens[i])) {
Daniel Jasperda16db32013-01-07 10:48:50 +0000888 Annotation.Type = TT_BinaryOperator;
Daniel Jasperab7654e2012-12-21 10:20:02 +0000889 } else if (Tok.Tok.is(tok::comment)) {
Manuel Klimekc74d2922013-01-07 08:54:53 +0000890 std::string Data(
891 Lexer::getSpelling(Tok.Tok, SourceMgr, Lex.getLangOpts()));
892 if (StringRef(Data).startswith("//"))
Daniel Jasperda16db32013-01-07 10:48:50 +0000893 Annotation.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000894 else
Daniel Jasperda16db32013-01-07 10:48:50 +0000895 Annotation.Type = TT_BlockComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000896 }
897 }
898 }
899
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 bool isBinaryOperator(const FormatToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000901 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000902 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000903 }
904
Daniel Jasperda16db32013-01-07 10:48:50 +0000905 TokenType determineStarAmpUsage(unsigned Index, bool IsRHS) {
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000906 if (Index == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000907 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000908 if (Index == Annotations.size())
Daniel Jasperda16db32013-01-07 10:48:50 +0000909 return TT_Unknown;
Daniel Jasper542de162013-01-02 15:46:59 +0000910 const FormatToken &PrevToken = Line.Tokens[Index - 1];
911 const FormatToken &NextToken = Line.Tokens[Index + 1];
Daniel Jasperf7935112012-12-03 18:12:45 +0000912
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000913 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
914 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
915 PrevToken.Tok.is(tok::colon) ||
Daniel Jasperda16db32013-01-07 10:48:50 +0000916 Annotations[Index - 1].Type == TT_BinaryOperator)
917 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000918
Daniel Jasper542de162013-01-02 15:46:59 +0000919 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000920 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
921 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
922 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
923 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000924 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000925
Daniel Jasper542de162013-01-02 15:46:59 +0000926 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
927 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000928 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000929
Daniel Jasper426702d2012-12-05 07:51:39 +0000930 // It is very unlikely that we are going to find a pointer or reference type
931 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000932 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000933 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000934
Daniel Jasperda16db32013-01-07 10:48:50 +0000935 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000936 }
937
Daniel Jasperda16db32013-01-07 10:48:50 +0000938 TokenType determinePlusMinusUsage(unsigned Index) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000939 // At the start of the line, +/- specific ObjectiveC method declarations.
940 if (Index == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000941 return TT_ObjCMethodSpecifier;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000942
943 // Use heuristics to recognize unary operators.
944 const Token &PreviousTok = Line.Tokens[Index - 1].Tok;
945 if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) ||
946 PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square) ||
Daniel Jasperda1c68a2013-01-02 15:26:16 +0000947 PreviousTok.is(tok::question) || PreviousTok.is(tok::colon) ||
948 PreviousTok.is(tok::kw_return) || PreviousTok.is(tok::kw_case))
Daniel Jasperda16db32013-01-07 10:48:50 +0000949 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000950
951 // There can't be to consecutive binary operators.
Daniel Jasperda16db32013-01-07 10:48:50 +0000952 if (Annotations[Index - 1].Type == TT_BinaryOperator)
953 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000954
955 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000956 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000957 }
958
959 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasperda16db32013-01-07 10:48:50 +0000960 TokenType determineIncrementUsage(unsigned Index) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000961 if (Index != 0 && Line.Tokens[Index - 1].Tok.is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +0000962 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000963
Daniel Jasperda16db32013-01-07 10:48:50 +0000964 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 }
966
967 bool spaceRequiredBetween(Token Left, Token Right) {
Daniel Jaspera4396862012-12-10 18:59:13 +0000968 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
969 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000970 if (Left.is(tok::kw_template) && Right.is(tok::less))
971 return true;
972 if (Left.is(tok::arrow) || Right.is(tok::arrow))
973 return false;
974 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
975 return false;
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000976 if (Left.is(tok::at) && Right.is(tok::identifier))
977 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000978 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
979 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000980 if (Right.is(tok::amp) || Right.is(tok::star))
981 return Left.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000982 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
983 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 if (Left.is(tok::amp) || Left.is(tok::star))
985 return Right.isLiteral() || Style.PointerAndReferenceBindToType;
986 if (Right.is(tok::star) && Left.is(tok::l_paren))
987 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000988 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
989 Right.is(tok::r_square))
990 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000991 if (Left.is(tok::coloncolon) ||
992 (Right.is(tok::coloncolon) &&
993 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 return false;
995 if (Left.is(tok::period) || Right.is(tok::period))
996 return false;
997 if (Left.is(tok::colon) || Right.is(tok::colon))
998 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 if (Left.is(tok::l_paren))
1000 return false;
1001 if (Left.is(tok::hash))
1002 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001003 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001004 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001005 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
1006 (Left.isNot(tok::identifier) && Left.isNot(tok::kw_sizeof) &&
Daniel Jasper3c0431c2013-01-02 17:21:36 +00001007 Left.isNot(tok::kw_typeof) && Left.isNot(tok::kw_alignof));
Daniel Jasperf7935112012-12-03 18:12:45 +00001008 }
1009 return true;
1010 }
1011
Daniel Jasperd1926a32013-01-02 08:44:14 +00001012 bool canBreakBefore(unsigned i) {
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001013 if (Annotations[i - 1].ClosesTemplateDeclaration)
1014 return true;
Daniel Jasperda16db32013-01-07 10:48:50 +00001015 if (Annotations[i - 1].Type == TT_PointerOrReference ||
1016 Annotations[i - 1].Type == TT_TemplateCloser ||
1017 Annotations[i].Type == TT_ConditionalExpr) {
Daniel Jasperd1926a32013-01-02 08:44:14 +00001018 return false;
1019 }
1020 const FormatToken &Left = Line.Tokens[i - 1];
1021 const FormatToken &Right = Line.Tokens[i];
Daniel Jasperda16db32013-01-07 10:48:50 +00001022 if (Left.Tok.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
1023 return false;
1024
Daniel Jaspere25509f2012-12-17 11:29:41 +00001025 if (Right.Tok.is(tok::r_paren) || Right.Tok.is(tok::l_brace) ||
1026 Right.Tok.is(tok::comment) || Right.Tok.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001027 return false;
Daniel Jasperab7654e2012-12-21 10:20:02 +00001028 return (isBinaryOperator(Left) && Left.Tok.isNot(tok::lessless)) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001029 Left.Tok.is(tok::comma) || Right.Tok.is(tok::lessless) ||
1030 Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period) ||
1031 Right.Tok.is(tok::colon) || Left.Tok.is(tok::semi) ||
1032 Left.Tok.is(tok::l_brace) ||
1033 (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001034 }
1035
1036 const UnwrappedLine &Line;
1037 FormatStyle Style;
1038 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001039 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001040 LineType CurrentLineType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 std::vector<TokenAnnotation> Annotations;
1042};
1043
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001044class LexerBasedFormatTokenSource : public FormatTokenSource {
1045public:
1046 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001047 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001048 IdentTable(Lex.getLangOpts()) {
1049 Lex.SetKeepWhitespaceMode(true);
1050 }
1051
1052 virtual FormatToken getNextToken() {
1053 if (GreaterStashed) {
1054 FormatTok.NewlinesBefore = 0;
1055 FormatTok.WhiteSpaceStart =
1056 FormatTok.Tok.getLocation().getLocWithOffset(1);
1057 FormatTok.WhiteSpaceLength = 0;
1058 GreaterStashed = false;
1059 return FormatTok;
1060 }
1061
1062 FormatTok = FormatToken();
1063 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001064 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001065 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001066 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1067 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001068
1069 // Consume and record whitespace until we find a significant token.
1070 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001071 FormatTok.NewlinesBefore += Text.count('\n');
1072 FormatTok.HasUnescapedNewline =
1073 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001074 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1075
1076 if (FormatTok.Tok.is(tok::eof))
1077 return FormatTok;
1078 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001079 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001080 }
Manuel Klimekef920692013-01-07 07:56:50 +00001081
1082 // Now FormatTok is the next non-whitespace token.
1083 FormatTok.TokenLength = Text.size();
1084
Manuel Klimek1abf7892013-01-04 23:34:14 +00001085 // In case the token starts with escaped newlines, we want to
1086 // take them into account as whitespace - this pattern is quite frequent
1087 // in macro definitions.
1088 // FIXME: What do we want to do with other escaped spaces, and escaped
1089 // spaces or newlines in the middle of tokens?
1090 // FIXME: Add a more explicit test.
1091 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001092 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001093 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001094 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001095 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001096 }
1097
1098 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001099 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001100 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001101 FormatTok.Tok.setKind(Info.getTokenID());
1102 }
1103
1104 if (FormatTok.Tok.is(tok::greatergreater)) {
1105 FormatTok.Tok.setKind(tok::greater);
1106 GreaterStashed = true;
1107 }
1108
1109 return FormatTok;
1110 }
1111
1112private:
1113 FormatToken FormatTok;
1114 bool GreaterStashed;
1115 Lexer &Lex;
1116 SourceManager &SourceMgr;
1117 IdentifierTable IdentTable;
1118
1119 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001120 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001121 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1122 Tok.getLength());
1123 }
1124};
1125
Daniel Jasperf7935112012-12-03 18:12:45 +00001126class Formatter : public UnwrappedLineConsumer {
1127public:
1128 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
1129 const std::vector<CharSourceRange> &Ranges)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001130 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), Ranges(Ranges),
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001131 StructuralError(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001132 }
1133
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001134 virtual ~Formatter() {
1135 }
1136
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001138 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
1139 UnwrappedLineParser Parser(Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001140 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001141 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001142 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1143 E = UnwrappedLines.end();
1144 I != E; ++I)
Manuel Klimek1abf7892013-01-04 23:34:14 +00001145 PreviousEndOfLineColumn =
1146 formatUnwrappedLine(*I, PreviousEndOfLineColumn);
Daniel Jasperf7935112012-12-03 18:12:45 +00001147 return Replaces;
1148 }
1149
1150private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001151 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001152 UnwrappedLines.push_back(TheLine);
1153 }
1154
Manuel Klimek1abf7892013-01-04 23:34:14 +00001155 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1156 unsigned PreviousEndOfLineColumn) {
1157 if (TheLine.Tokens.empty())
1158 return 0; // FIXME: Find out how this can ever happen.
Daniel Jasperf7935112012-12-03 18:12:45 +00001159
1160 CharSourceRange LineRange =
1161 CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(),
1162 TheLine.Tokens.back().Tok.getLocation());
1163
1164 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1165 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1166 Ranges[i].getBegin()) ||
1167 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1168 LineRange.getBegin()))
1169 continue;
1170
Manuel Klimekc74d2922013-01-07 08:54:53 +00001171 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasperc0880a92013-01-04 18:52:56 +00001172 if (!Annotator.annotate())
Manuel Klimek1abf7892013-01-04 23:34:14 +00001173 break;
1174 UnwrappedLineFormatter Formatter(
1175 Style, SourceMgr, TheLine, PreviousEndOfLineColumn,
Daniel Jasperda16db32013-01-07 10:48:50 +00001176 Annotator.getLineType(), Annotator.getAnnotations(), Replaces,
1177 StructuralError);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001178 return Formatter.format();
Daniel Jasperf7935112012-12-03 18:12:45 +00001179 }
Manuel Klimek1abf7892013-01-04 23:34:14 +00001180 // If we did not reformat this unwrapped line, the column at the end of the
1181 // last token is unchanged - thus, we can calculate the end of the last
1182 // token, and return the result.
1183 const FormatToken &Token = TheLine.Tokens.back();
1184 return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) +
1185 Lex.MeasureTokenLength(Token.Tok.getLocation(), SourceMgr,
1186 Lex.getLangOpts()) -
1187 1;
Daniel Jasperf7935112012-12-03 18:12:45 +00001188 }
1189
1190 FormatStyle Style;
1191 Lexer &Lex;
1192 SourceManager &SourceMgr;
1193 tooling::Replacements Replaces;
1194 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001195 std::vector<UnwrappedLine> UnwrappedLines;
1196 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001197};
1198
1199tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1200 SourceManager &SourceMgr,
1201 std::vector<CharSourceRange> Ranges) {
1202 Formatter formatter(Style, Lex, SourceMgr, Ranges);
1203 return formatter.format();
1204}
1205
1206} // namespace format
1207} // namespace clang