blob: d721536c76ba659c95283c027f92b59c4e97639c [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"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000021#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000022#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000023#include "clang/Basic/SourceManager.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000024#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000025#include "clang/Lex/Lexer.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000026#include <string>
27
Daniel Jasperf7935112012-12-03 18:12:45 +000028namespace clang {
29namespace format {
30
Daniel Jasperda16db32013-01-07 10:48:50 +000031enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000032 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000033 TT_BlockComment,
34 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000035 TT_ConditionalExpr,
36 TT_CtorInitializerColon,
Daniel Jasperda16db32013-01-07 10:48:50 +000037 TT_DirectorySeparator,
Daniel Jasper7194e182013-01-10 11:14:08 +000038 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000039 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000040 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000041 TT_ObjCMethodSpecifier,
42 TT_OverloadedOperator,
43 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000044 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000045 TT_TemplateCloser,
46 TT_TemplateOpener,
47 TT_TrailingUnaryOperator,
48 TT_UnaryOperator,
49 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000050};
51
52enum LineType {
53 LT_Invalid,
54 LT_Other,
55 LT_PreprocessorDirective,
56 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000057 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Daniel Jasperda16db32013-01-07 10:48:50 +000058 LT_ObjCMethodDecl
59};
60
Daniel Jasper7c85fde2013-01-08 14:56:18 +000061class AnnotatedToken {
62public:
63 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000064 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
65 CanBreakBefore(false), MustBreakBefore(false),
66 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000067
68 bool is(tok::TokenKind Kind) const {
69 return FormatTok.Tok.is(Kind);
70 }
71 bool isNot(tok::TokenKind Kind) const {
72 return FormatTok.Tok.isNot(Kind);
73 }
74 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
75 return FormatTok.Tok.isObjCAtKeyword(Kind);
76 }
77
78 FormatToken FormatTok;
79
Daniel Jasperf7935112012-12-03 18:12:45 +000080 TokenType Type;
81
Daniel Jasperf7935112012-12-03 18:12:45 +000082 bool SpaceRequiredBefore;
83 bool CanBreakBefore;
84 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000085
86 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000087
88 std::vector<AnnotatedToken> Children;
89 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000090};
91
Daniel Jasper7c85fde2013-01-08 14:56:18 +000092static prec::Level getPrecedence(const AnnotatedToken &Tok) {
93 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000094}
95
Daniel Jasperf7935112012-12-03 18:12:45 +000096using llvm::MutableArrayRef;
97
98FormatStyle getLLVMStyle() {
99 FormatStyle LLVMStyle;
100 LLVMStyle.ColumnLimit = 80;
101 LLVMStyle.MaxEmptyLinesToKeep = 1;
102 LLVMStyle.PointerAndReferenceBindToType = false;
103 LLVMStyle.AccessModifierOffset = -2;
104 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000105 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000106 LLVMStyle.SpacesBeforeTrailingComments = 1;
Nico Webera6087752013-01-10 20:12:55 +0000107 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000108 return LLVMStyle;
109}
110
111FormatStyle getGoogleStyle() {
112 FormatStyle GoogleStyle;
113 GoogleStyle.ColumnLimit = 80;
114 GoogleStyle.MaxEmptyLinesToKeep = 1;
115 GoogleStyle.PointerAndReferenceBindToType = true;
116 GoogleStyle.AccessModifierOffset = -1;
117 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000118 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000119 GoogleStyle.SpacesBeforeTrailingComments = 2;
Nico Webera6087752013-01-10 20:12:55 +0000120 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000121 return GoogleStyle;
122}
123
124struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000125 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000126 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000127 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000128};
129
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000130/// \brief Replaces the whitespace in front of \p Tok. Only call once for
131/// each \c FormatToken.
132static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
133 unsigned Spaces, const FormatStyle &Style,
134 SourceManager &SourceMgr,
135 tooling::Replacements &Replaces) {
136 Replaces.insert(tooling::Replacement(
137 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
138 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
139}
140
141/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
142/// backslashes to escape newlines inside a preprocessor directive.
143///
144/// This function and \c replaceWhitespace have the same behavior if
145/// \c Newlines == 0.
146static void replacePPWhitespace(
147 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
148 unsigned WhitespaceStartColumn, const FormatStyle &Style,
149 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
150 std::string NewLineText;
151 if (NewLines > 0) {
152 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
153 WhitespaceStartColumn);
154 for (unsigned i = 0; i < NewLines; ++i) {
155 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
156 NewLineText += "\\\n";
157 Offset = 0;
158 }
159 }
160 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
161 Tok.FormatTok.WhiteSpaceLength,
162 NewLineText + std::string(Spaces, ' ')));
163}
164
Daniel Jasperf7935112012-12-03 18:12:45 +0000165class UnwrappedLineFormatter {
166public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000167 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
168 const UnwrappedLine &Line, unsigned FirstIndent,
169 bool FitsOnALine, LineType CurrentLineType,
170 const AnnotatedToken &RootToken,
171 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000172 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000173 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000174 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000175 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000176 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000177 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000178 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000179 }
180
Manuel Klimek1abf7892013-01-04 23:34:14 +0000181 /// \brief Formats an \c UnwrappedLine.
182 ///
183 /// \returns The column after the last token in the last line of the
184 /// \c UnwrappedLine.
185 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000186 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000187 IndentState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000188 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000189 State.NextToken = &RootToken;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000190 State.Indent.push_back(FirstIndent + 4);
191 State.LastSpace.push_back(FirstIndent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000192 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000193 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000194 State.ForLoopVariablePos = 0;
195 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000196 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000197
198 // The first token has already been indented and thus consumed.
199 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000200
201 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000202 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000203 if (FitsOnALine) {
204 addTokenToState(false, false, State);
205 } else {
206 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
207 unsigned Break = calcPenalty(State, true, NoBreak);
208 addTokenToState(Break < NoBreak, false, State);
209 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000210 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000211 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000212 }
213
214private:
215 /// \brief The current state when indenting a unwrapped line.
216 ///
217 /// As the indenting tries different combinations this is copied by value.
218 struct IndentState {
219 /// \brief The number of used columns in the current line.
220 unsigned Column;
221
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000222 const AnnotatedToken *NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000223
Daniel Jasper6d822722012-12-24 16:43:00 +0000224 /// \brief The parenthesis level of the first token on the current line.
225 unsigned StartOfLineLevel;
226
Daniel Jasperf7935112012-12-03 18:12:45 +0000227 /// \brief The position to which a specific parenthesis level needs to be
228 /// indented.
229 std::vector<unsigned> Indent;
230
Daniel Jaspere9de2602012-12-06 09:56:08 +0000231 /// \brief The position of the last space on each level.
232 ///
233 /// Used e.g. to break like:
234 /// functionCall(Parameter, otherCall(
235 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000236 std::vector<unsigned> LastSpace;
237
Daniel Jaspere9de2602012-12-06 09:56:08 +0000238 /// \brief The position the first "<<" operator encountered on each level.
239 ///
240 /// Used to align "<<" operators. 0 if no such operator has been encountered
241 /// on a level.
242 std::vector<unsigned> FirstLessLess;
243
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000244 /// \brief Whether a newline needs to be inserted before the block's closing
245 /// brace.
246 ///
247 /// We only want to insert a newline before the closing brace if there also
248 /// was a newline after the beginning left brace.
249 std::vector<bool> BreakBeforeClosingBrace;
250
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000251 /// \brief The column of the first variable in a for-loop declaration.
252 ///
253 /// Used to align the second variable if necessary.
254 unsigned ForLoopVariablePos;
255
256 /// \brief \c true if this line contains a continued for-loop section.
257 bool LineContainsContinuedForLoopSection;
258
Daniel Jasperf7935112012-12-03 18:12:45 +0000259 /// \brief Comparison operator to be able to used \c IndentState in \c map.
260 bool operator<(const IndentState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000261 if (Other.NextToken != NextToken)
262 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000263 if (Other.Column != Column)
264 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000265 if (Other.StartOfLineLevel != StartOfLineLevel)
266 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000267 if (Other.Indent.size() != Indent.size())
268 return Other.Indent.size() > Indent.size();
269 for (int i = 0, e = Indent.size(); i != e; ++i) {
270 if (Other.Indent[i] != Indent[i])
271 return Other.Indent[i] > Indent[i];
272 }
273 if (Other.LastSpace.size() != LastSpace.size())
274 return Other.LastSpace.size() > LastSpace.size();
275 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
276 if (Other.LastSpace[i] != LastSpace[i])
277 return Other.LastSpace[i] > LastSpace[i];
278 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000279 if (Other.FirstLessLess.size() != FirstLessLess.size())
280 return Other.FirstLessLess.size() > FirstLessLess.size();
281 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
282 if (Other.FirstLessLess[i] != FirstLessLess[i])
283 return Other.FirstLessLess[i] > FirstLessLess[i];
284 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000285 if (Other.ForLoopVariablePos != ForLoopVariablePos)
286 return Other.ForLoopVariablePos < ForLoopVariablePos;
287 if (Other.LineContainsContinuedForLoopSection !=
288 LineContainsContinuedForLoopSection)
289 return LineContainsContinuedForLoopSection;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000290 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
291 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000292 return false;
293 }
294 };
295
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000296 /// \brief Appends the next token to \p State and updates information
297 /// necessary for indentation.
298 ///
299 /// Puts the token on the current line if \p Newline is \c true and adds a
300 /// line break and necessary indentation otherwise.
301 ///
302 /// If \p DryRun is \c false, also creates and stores the required
303 /// \c Replacement.
304 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000305 const AnnotatedToken &Current = *State.NextToken;
306 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weber51306d22013-01-10 00:25:19 +0000307 assert(State.Indent.size());
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000308 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000309
310 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000311 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000312 if (Current.is(tok::r_brace)) {
313 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000314 } else if (Current.is(tok::string_literal) &&
315 Previous.is(tok::string_literal)) {
316 State.Column = State.Column - Previous.FormatTok.TokenLength;
317 } else if (Current.is(tok::lessless) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000318 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000319 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000320 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000321 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
322 Current.is(tok::period) || Previous.is(tok::question) ||
323 Previous.Type == TT_ConditionalExpr)) {
324 // Indent and extra 4 spaces after if we know the current expression is
325 // continued. Don't do that on the top level, as we already indent 4
326 // there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000327 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000328 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000329 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000330 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000331 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000332 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000333 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000334 }
335
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000336 // A line starting with a closing brace is assumed to be correct for the
337 // same level as before the opening brace.
338 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000339
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000340 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000341 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000342
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000343 if (!DryRun) {
344 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000345 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
346 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000347 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000348 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000349 WhitespaceStartColumn, Style, SourceMgr,
350 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000351 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000352
Daniel Jasper89058942013-01-09 09:50:48 +0000353 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000354 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000355 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000356 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000357 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000358 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
359 State.ForLoopVariablePos = State.Column -
360 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000361
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000362 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
363 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000364 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000365
Daniel Jasperf7935112012-12-03 18:12:45 +0000366 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000367 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000368
Daniel Jasperbcab4302013-01-09 10:40:23 +0000369 // FIXME: Do we need to do this for assignments nested in other
370 // expressions?
371 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000372 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000373 Previous.is(tok::kw_return)))
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000374 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000375 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000376 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000377 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000378 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000379
Daniel Jasper206df732013-01-07 13:08:40 +0000380 // Top-level spaces that are not part of assignments are exempt as that
381 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000382 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000383 if (Spaces > 0 &&
384 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000385 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000386 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000387 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000388 if (Newline && Previous.is(tok::l_brace)) {
389 State.BreakBeforeClosingBrace.back() = true;
390 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000391 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000392
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000393 /// \brief Mark the next token as consumed in \p State and modify its stacks
394 /// accordingly.
395 void moveStateToNextToken(IndentState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000396 const AnnotatedToken &Current = *State.NextToken;
Nico Weber51306d22013-01-10 00:25:19 +0000397 assert(State.Indent.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000398 unsigned ParenLevel = State.Indent.size() - 1;
399
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000400 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000401 State.FirstLessLess[ParenLevel] = State.Column;
402
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000403 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000404 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000405 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
406 Current.is(tok::l_brace) ||
407 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000408 if (Current.is(tok::l_brace)) {
409 // FIXME: This does not work with nested static initializers.
410 // Implement a better handling for static initializers and similar
411 // constructs.
412 State.Indent.push_back(Line.Level * 2 + 2);
413 } else {
414 State.Indent.push_back(4 + State.LastSpace.back());
415 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000416 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000417 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000418 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000419 }
420
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000421 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000422 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000423 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
424 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
425 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 State.Indent.pop_back();
427 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000428 State.FirstLessLess.pop_back();
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000429 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000430 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000431
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000432 if (State.NextToken->Children.empty())
433 State.NextToken = NULL;
434 else
435 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000436
437 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000438 }
439
Nico Weber49cbc2c2013-01-07 15:15:29 +0000440 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000441 unsigned splitPenalty(const AnnotatedToken &Tok) {
442 const AnnotatedToken &Left = Tok;
443 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000444
445 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000446 if (RootToken.is(tok::kw_for) &&
447 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000448 return 20;
449
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000450 if (Left.is(tok::semi) || Left.is(tok::comma) ||
451 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000452 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000453 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000454 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000455
Daniel Jasper399d24b2013-01-09 07:06:56 +0000456 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
457 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000458 prec::Level Level = getPrecedence(Left);
459
460 // Breaking after an assignment leads to a bad result as the two sides of
461 // the assignment are visually very close together.
462 if (Level == prec::Assignment)
463 return 50;
464
Daniel Jasperde5c2072012-12-24 00:13:23 +0000465 if (Level != prec::Unknown)
466 return Level;
467
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000468 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000469 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000470
Daniel Jasperf7935112012-12-03 18:12:45 +0000471 return 3;
472 }
473
Daniel Jasper2df93312013-01-09 10:16:05 +0000474 unsigned getColumnLimit() {
475 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
476 }
477
Daniel Jasperf7935112012-12-03 18:12:45 +0000478 /// \brief Calculate the number of lines needed to format the remaining part
479 /// of the unwrapped line.
480 ///
481 /// Assumes the formatting so far has led to
482 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
483 /// added after the previous token.
484 ///
485 /// \param StopAt is used for optimization. If we can determine that we'll
486 /// definitely need at least \p StopAt additional lines, we already know of a
487 /// better solution.
488 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
489 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000490 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000491 return 0;
492
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000493 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000494 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000495 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000496 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000497 if (!NewLine && State.NextToken->is(tok::r_brace) &&
498 State.BreakBeforeClosingBrace.back())
499 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000500 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000501 State.LineContainsContinuedForLoopSection)
502 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000503
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000504 unsigned CurrentPenalty = 0;
505 if (NewLine) {
506 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000507 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000508 } else {
509 if (State.Indent.size() < State.StartOfLineLevel)
510 CurrentPenalty += Parameters.PenaltyLevelDecrease *
511 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000512 }
513
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000514 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000515
Daniel Jasper2df93312013-01-09 10:16:05 +0000516 // Exceeding column limit is bad, assign penalty.
517 if (State.Column > getColumnLimit()) {
518 unsigned ExcessCharacters = State.Column - getColumnLimit();
519 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
520 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000521
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 if (StopAt <= CurrentPenalty)
523 return UINT_MAX;
524 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000526 if (I != Memory.end()) {
527 // If this state has already been examined, we can safely return the
528 // previous result if we
529 // - have not hit the optimatization (and thus returned UINT_MAX) OR
530 // - are now computing for a smaller or equal StopAt.
531 unsigned SavedResult = I->second.first;
532 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000533 if (SavedResult != UINT_MAX)
534 return SavedResult + CurrentPenalty;
535 else if (StopAt <= SavedStopAt)
536 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000537 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000538
539 unsigned NoBreak = calcPenalty(State, false, StopAt);
540 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
541 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000542
543 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
544 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000545 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000546
547 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000548 }
549
Daniel Jasperf7935112012-12-03 18:12:45 +0000550 FormatStyle Style;
551 SourceManager &SourceMgr;
552 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000553 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000554 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000555 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000556 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000557 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000558
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000559 // A map from an indent state to a pair (Result, Used-StopAt).
560 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
561 StateMap Memory;
562
Daniel Jasperf7935112012-12-03 18:12:45 +0000563 OptimizationParameters Parameters;
564};
565
566/// \brief Determines extra information about the tokens comprising an
567/// \c UnwrappedLine.
568class TokenAnnotator {
569public:
570 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000571 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
573 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000574 }
575
576 /// \brief A parser that gathers additional information about tokens.
577 ///
578 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
579 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
580 /// into template parameter lists.
581 class AnnotatingParser {
582 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000583 AnnotatingParser(AnnotatedToken &RootToken)
584 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000585 }
586
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000587 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000588 while (CurrentToken != NULL) {
589 if (CurrentToken->is(tok::greater)) {
590 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 next();
592 return true;
593 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000594 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
595 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000596 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000597 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
598 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000600 if (!consumeToken())
601 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000602 }
603 return false;
604 }
605
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000606 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000607 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
608 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000609 while (CurrentToken != NULL) {
610 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 next();
612 return true;
613 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000614 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000615 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000616 if (!consumeToken())
617 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000618 }
619 return false;
620 }
621
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000622 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000623 while (CurrentToken != NULL) {
624 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000625 next();
626 return true;
627 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000629 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000630 if (!consumeToken())
631 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000632 }
633 return false;
634 }
635
Daniel Jasper83a54d22013-01-10 09:26:47 +0000636 bool parseBrace() {
637 while (CurrentToken != NULL) {
638 if (CurrentToken->is(tok::r_brace)) {
639 next();
640 return true;
641 }
642 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
643 return false;
644 if (!consumeToken())
645 return false;
646 }
647 // Lines can currently end with '{'.
648 return true;
649 }
650
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000651 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000652 while (CurrentToken != NULL) {
653 if (CurrentToken->is(tok::colon)) {
654 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000655 next();
656 return true;
657 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000658 if (!consumeToken())
659 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 }
661 return false;
662 }
663
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000664 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000665 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
666 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000667 next();
668 if (!parseAngle())
669 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000671 parseLine();
672 return true;
673 }
674 return false;
675 }
676
Daniel Jasperc0880a92013-01-04 18:52:56 +0000677 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000678 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000679 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000681 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000682 if (!parseParens())
683 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000684 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
685 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000686 next();
687 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000688 break;
689 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000690 if (!parseSquare())
691 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000693 case tok::l_brace:
694 if (!parseBrace())
695 return false;
696 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000697 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000698 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000699 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000701 Tok->Type = TT_BinaryOperator;
702 CurrentToken = Tok;
703 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000704 }
705 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000706 case tok::r_paren:
707 case tok::r_square:
708 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000709 case tok::r_brace:
710 // Lines can start with '}'.
711 if (Tok->Parent != NULL)
712 return false;
713 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000715 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000716 break;
717 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000718 if (CurrentToken->is(tok::l_paren)) {
719 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000720 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000721 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
722 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000723 next();
724 }
725 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000726 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
727 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000728 next();
729 }
730 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000731 break;
732 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000733 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000734 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000735 case tok::kw_template:
736 parseTemplateDeclaration();
737 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 default:
739 break;
740 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000741 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 }
743
Daniel Jasper050948a52012-12-21 17:58:39 +0000744 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000745 while (CurrentToken != NULL) {
746 if (CurrentToken->is(tok::slash))
747 CurrentToken->Type = TT_DirectorySeparator;
748 else if (CurrentToken->is(tok::less))
749 CurrentToken->Type = TT_TemplateOpener;
750 else if (CurrentToken->is(tok::greater))
751 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000752 next();
753 }
754 }
755
756 void parsePreprocessorDirective() {
757 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000759 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000760 // Hashes in the middle of a line can lead to any strange token
761 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000762 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000763 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 switch (
765 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000766 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000767 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000768 parseIncludeDirective();
769 break;
770 default:
771 break;
772 }
773 }
774
Daniel Jasperda16db32013-01-07 10:48:50 +0000775 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000777 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000778 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000779 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000780 while (CurrentToken != NULL) {
781 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000782 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000783 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000784 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000786 if (KeywordVirtualFound)
787 return LT_VirtualFunctionDecl;
788 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000789 }
790
791 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000792 if (CurrentToken != NULL && !CurrentToken->Children.empty())
793 CurrentToken = &CurrentToken->Children[0];
794 else
795 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000796 }
797
798 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000799 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000800 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000801 };
802
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000803 void createAnnotatedTokens(AnnotatedToken &Current) {
804 if (!Current.FormatTok.Children.empty()) {
805 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
806 Current.Children.back().Parent = &Current;
807 createAnnotatedTokens(Current.Children.back());
808 }
809 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000810
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000811 void calculateExtraInformation(AnnotatedToken &Current) {
812 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
813
Manuel Klimek52b15152013-01-09 15:25:02 +0000814 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000815 Current.MustBreakBefore = true;
816 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000817 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
818 TT_LineComment || (Current.is(tok::string_literal) &&
819 Current.Parent->is(tok::string_literal))) {
820 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000821 } else {
822 Current.MustBreakBefore = false;
823 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000824 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000825 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000826 if (!Current.Children.empty())
827 calculateExtraInformation(Current.Children[0]);
828 }
829
830 bool annotate() {
831 createAnnotatedTokens(RootToken);
832
833 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000834 CurrentLineType = Parser.parseLine();
835 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000836 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000837
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000838 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000839
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000840 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000841 CurrentLineType = LT_ObjCMethodDecl;
Nico Weber2bb00742013-01-10 19:19:14 +0000842 else if (RootToken.Type == TT_ObjCDecl)
843 CurrentLineType = LT_ObjCDecl;
Daniel Jasperda16db32013-01-07 10:48:50 +0000844
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 if (!RootToken.Children.empty())
846 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000847 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000848 }
849
Daniel Jasperda16db32013-01-07 10:48:50 +0000850 LineType getLineType() {
851 return CurrentLineType;
852 }
853
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000854 const AnnotatedToken &getRootToken() {
855 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000856 }
857
858private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000859 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
860 if (getPrecedence(Current) == prec::Assignment ||
861 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
862 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000863
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 if (Current.Type == TT_Unknown) {
865 if (Current.is(tok::star) || Current.is(tok::amp)) {
866 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000867 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
868 Current.is(tok::caret)) {
869 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
871 Current.Type = determineIncrementUsage(Current);
872 } else if (Current.is(tok::exclaim)) {
873 Current.Type = TT_UnaryOperator;
874 } else if (isBinaryOperator(Current)) {
875 Current.Type = TT_BinaryOperator;
876 } else if (Current.is(tok::comment)) {
877 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
878 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000879 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000880 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000881 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000882 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000883 } else if (Current.is(tok::r_paren) &&
884 (Current.Parent->Type == TT_PointerOrReference ||
885 Current.Parent->Type == TT_TemplateCloser)) {
886 // FIXME: We need to get smarter and understand more cases of casts.
887 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +0000888 } else if (Current.is(tok::at) && Current.Children.size()) {
889 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
890 case tok::objc_interface:
891 case tok::objc_implementation:
892 case tok::objc_protocol:
893 Current.Type = TT_ObjCDecl;
894 default:
895 break;
896 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000897 }
898 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000899
900 if (!Current.Children.empty())
901 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000902 }
903
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000904 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000905 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000906 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000907 }
908
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000909 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
910 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000911 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000912 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000913 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000914 const FormatToken &PrevToken = Tok.Parent->FormatTok;
915 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000916
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000917 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
918 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000919 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
920 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000921 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000922
Daniel Jasper542de162013-01-02 15:46:59 +0000923 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000924 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
925 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
926 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
927 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000928 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000929
Daniel Jasper542de162013-01-02 15:46:59 +0000930 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
931 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000932 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000933
Daniel Jasper426702d2012-12-05 07:51:39 +0000934 // It is very unlikely that we are going to find a pointer or reference type
935 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000936 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000937 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000938
Daniel Jasperda16db32013-01-07 10:48:50 +0000939 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000940 }
941
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000942 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000943 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000944 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000945 return TT_ObjCMethodSpecifier;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000946
947 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
949 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
950 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
Nico Webera1a5abd2013-01-10 19:36:35 +0000951 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case) ||
952 Tok.Parent->is(tok::at))
Daniel Jasperda16db32013-01-07 10:48:50 +0000953 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000954
955 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000956 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +0000957 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000958
959 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000960 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000961 }
962
963 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
965 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +0000966 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000967
Daniel Jasperda16db32013-01-07 10:48:50 +0000968 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000969 }
970
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000971 bool spaceRequiredBetween(const AnnotatedToken &Left,
972 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +0000973 if (Right.is(tok::hashhash))
974 return Left.is(tok::hash);
975 if (Left.is(tok::hashhash) || Left.is(tok::hash))
976 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +0000977 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
978 return false;
Nico Webera6087752013-01-10 20:12:55 +0000979 if (Right.is(tok::less) &&
980 (Left.is(tok::kw_template) ||
981 (CurrentLineType == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +0000982 return true;
983 if (Left.is(tok::arrow) || Right.is(tok::arrow))
984 return false;
985 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
986 return false;
Nico Weber77aa2502013-01-08 19:40:21 +0000987 if (Left.is(tok::at) &&
988 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
989 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000990 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
991 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000992 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000993 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
994 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000995 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000996 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000997 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
998 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001000 return Right.FormatTok.Tok.isLiteral() ||
1001 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001002 if (Right.is(tok::star) && Left.is(tok::l_paren))
1003 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001004 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
1005 Right.is(tok::r_square))
1006 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001007 if (Left.is(tok::coloncolon) ||
1008 (Right.is(tok::coloncolon) &&
1009 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +00001010 return false;
1011 if (Left.is(tok::period) || Right.is(tok::period))
1012 return false;
1013 if (Left.is(tok::colon) || Right.is(tok::colon))
1014 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001015 if (Left.is(tok::l_paren))
1016 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 if (Right.is(tok::l_paren)) {
Nico Weber2bb00742013-01-10 19:19:14 +00001018 return CurrentLineType == LT_ObjCDecl || Left.is(tok::kw_if) ||
1019 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
1020 Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001021 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001022 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001023 if (Left.is(tok::at) &&
1024 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001025 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001026 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1027 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001028 return true;
1029 }
1030
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001032 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001033 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1034 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001035 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001037 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001038 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001039 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001040 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001041 // Don't space between ')' and <id>
1042 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001043 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001044 // Don't space between ':' and '('
1045 return false;
1046 }
1047
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001048 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001049 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001050 if (Tok.Type == TT_OverloadedOperator)
1051 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001052 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001054 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001055 if (Tok.is(tok::colon))
1056 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001057 if (Tok.Parent->Type == TT_UnaryOperator ||
1058 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001059 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001060 if (Tok.Type == TT_UnaryOperator)
1061 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webera1a5abd2013-01-10 19:36:35 +00001062 Tok.Parent->isNot(tok::l_square) &&
1063 Tok.Parent->isNot(tok::at);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001064 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1065 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001066 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1067 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 if (Tok.Type == TT_DirectorySeparator ||
1069 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001070 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001071 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001072 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001073 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001074 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001075 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001076 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001078 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001079 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001080 }
1081
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001082 bool canBreakBefore(const AnnotatedToken &Right) {
1083 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001084 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001085 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1086 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001087 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001088 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1089 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001090 // Don't break this identifier as ':' or identifier
1091 // before it will break.
1092 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001093 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1094 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001095 // Don't break at ':' if identifier before it can beak.
1096 return false;
1097 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001098 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001099 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001100 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001101 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001102 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001103 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001104 return false;
1105
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001106 if (Right.is(tok::comment))
1107 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001108 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001109 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001110 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001111 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1112 Left.is(tok::comma) || Right.is(tok::lessless) ||
1113 Right.is(tok::arrow) || Right.is(tok::period) ||
1114 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001115 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001116 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001118 }
1119
Daniel Jasperf7935112012-12-03 18:12:45 +00001120 FormatStyle Style;
1121 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001122 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001123 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001125};
1126
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001127class LexerBasedFormatTokenSource : public FormatTokenSource {
1128public:
1129 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001130 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001131 IdentTable(Lex.getLangOpts()) {
1132 Lex.SetKeepWhitespaceMode(true);
1133 }
1134
1135 virtual FormatToken getNextToken() {
1136 if (GreaterStashed) {
1137 FormatTok.NewlinesBefore = 0;
1138 FormatTok.WhiteSpaceStart =
1139 FormatTok.Tok.getLocation().getLocWithOffset(1);
1140 FormatTok.WhiteSpaceLength = 0;
1141 GreaterStashed = false;
1142 return FormatTok;
1143 }
1144
1145 FormatTok = FormatToken();
1146 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001147 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001148 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001149 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1150 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001151
1152 // Consume and record whitespace until we find a significant token.
1153 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001154 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001155 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1156 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001157 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1158
1159 if (FormatTok.Tok.is(tok::eof))
1160 return FormatTok;
1161 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001162 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001163 }
Manuel Klimekef920692013-01-07 07:56:50 +00001164
1165 // Now FormatTok is the next non-whitespace token.
1166 FormatTok.TokenLength = Text.size();
1167
Manuel Klimek1abf7892013-01-04 23:34:14 +00001168 // In case the token starts with escaped newlines, we want to
1169 // take them into account as whitespace - this pattern is quite frequent
1170 // in macro definitions.
1171 // FIXME: What do we want to do with other escaped spaces, and escaped
1172 // spaces or newlines in the middle of tokens?
1173 // FIXME: Add a more explicit test.
1174 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001175 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001176 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001177 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001178 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001179 }
1180
1181 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001182 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001183 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184 FormatTok.Tok.setKind(Info.getTokenID());
1185 }
1186
1187 if (FormatTok.Tok.is(tok::greatergreater)) {
1188 FormatTok.Tok.setKind(tok::greater);
1189 GreaterStashed = true;
1190 }
1191
1192 return FormatTok;
1193 }
1194
1195private:
1196 FormatToken FormatTok;
1197 bool GreaterStashed;
1198 Lexer &Lex;
1199 SourceManager &SourceMgr;
1200 IdentifierTable IdentTable;
1201
1202 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001203 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001204 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1205 Tok.getLength());
1206 }
1207};
1208
Daniel Jasperf7935112012-12-03 18:12:45 +00001209class Formatter : public UnwrappedLineConsumer {
1210public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001211 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1212 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001213 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001214 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001215 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001216
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001217 virtual ~Formatter() {
1218 }
1219
Daniel Jasperf7935112012-12-03 18:12:45 +00001220 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001221 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001222 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001223 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001224 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001225 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1226 E = UnwrappedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001227 I != E; ++I) {
1228 const UnwrappedLine &TheLine = *I;
1229 if (touchesRanges(TheLine)) {
1230 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
1231 if (!Annotator.annotate())
1232 break;
1233 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1234 TheLine.Level, TheLine.InPPDirective,
1235 PreviousEndOfLineColumn);
1236 bool FitsOnALine = fitsOnALine(Annotator.getRootToken(), Indent,
1237 TheLine.InPPDirective);
1238 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
1239 FitsOnALine, Annotator.getLineType(),
1240 Annotator.getRootToken(), Replaces,
1241 StructuralError);
1242 PreviousEndOfLineColumn = Formatter.format();
1243 } else {
1244 // If we did not reformat this unwrapped line, the column at the end of
1245 // the last token is unchanged - thus, we can calculate the end of the
1246 // last token, and return the result.
1247 const FormatToken *Last = getLastLine(TheLine);
1248 PreviousEndOfLineColumn =
1249 SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1250 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
1251 Lex.getLangOpts()) -
1252 1;
1253 }
1254 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001255 return Replaces;
1256 }
1257
1258private:
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001259 const FormatToken *getLastLine(const UnwrappedLine &TheLine) {
1260 const FormatToken *Last = &TheLine.RootToken;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001261 while (!Last->Children.empty())
1262 Last = &Last->Children.back();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001263 return Last;
1264 }
1265
1266 bool touchesRanges(const UnwrappedLine &TheLine) {
1267 const FormatToken *First = &TheLine.RootToken;
1268 const FormatToken *Last = getLastLine(TheLine);
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001269 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001270 First->Tok.getLocation(),
1271 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001272 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001273 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1274 Ranges[i].getBegin()) &&
1275 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1276 LineRange.getBegin()))
1277 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001278 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001279 return false;
1280 }
1281
1282 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
1283 UnwrappedLines.push_back(TheLine);
Daniel Jasperf7935112012-12-03 18:12:45 +00001284 }
1285
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +00001286 bool fitsOnALine(const AnnotatedToken &RootToken, unsigned Indent,
1287 bool InPPDirective) {
1288 // Check whether the UnwrappedLine can be put onto a single line. If so,
1289 // this is bound to be the optimal solution (by definition) and we don't
1290 // need to analyze the entire solution space.
1291 unsigned Columns = Indent + RootToken.FormatTok.TokenLength;
1292 bool FitsOnALine = true;
1293 const AnnotatedToken *Tok = &RootToken;
1294 while (Tok != NULL) {
1295 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
1296 Tok->FormatTok.TokenLength;
1297 // A special case for the colon of a constructor initializer as this only
1298 // needs to be put on a new line if the line needs to be split.
1299 if (Columns > Style.ColumnLimit - (InPPDirective ? 1 : 0) ||
1300 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
1301 FitsOnALine = false;
1302 break;
1303 }
1304 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
1305 }
1306 return FitsOnALine;
1307 }
1308
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001309 /// \brief Add a new line and the required indent before the first Token
1310 /// of the \c UnwrappedLine if there was no structural parsing error.
1311 /// Returns the indent level of the \c UnwrappedLine.
1312 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1313 bool InPPDirective,
1314 unsigned PreviousEndOfLineColumn) {
1315 const FormatToken& Tok = RootToken.FormatTok;
1316 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1317 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1318
1319 unsigned Newlines = std::min(Tok.NewlinesBefore,
1320 Style.MaxEmptyLinesToKeep + 1);
1321 if (Newlines == 0 && !Tok.IsFirst)
1322 Newlines = 1;
1323 unsigned Indent = Level * 2;
1324
1325 bool IsAccessModifier = false;
1326 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1327 RootToken.is(tok::kw_private))
1328 IsAccessModifier = true;
1329 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1330 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1331 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1332 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1333 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1334 IsAccessModifier = true;
1335
1336 if (IsAccessModifier &&
1337 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1338 Indent += Style.AccessModifierOffset;
1339 if (!InPPDirective || Tok.HasUnescapedNewline) {
1340 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1341 } else {
1342 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1343 SourceMgr, Replaces);
1344 }
1345 return Indent;
1346 }
1347
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001348 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001349 FormatStyle Style;
1350 Lexer &Lex;
1351 SourceManager &SourceMgr;
1352 tooling::Replacements Replaces;
1353 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001354 std::vector<UnwrappedLine> UnwrappedLines;
1355 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001356};
1357
1358tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1359 SourceManager &SourceMgr,
1360 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001361 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1362 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1363 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1364 DiagnosticsEngine Diagnostics(
1365 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1366 &DiagnosticPrinter, false);
1367 Diagnostics.setSourceManager(&SourceMgr);
1368 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001369 return formatter.format();
1370}
1371
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001372LangOptions getFormattingLangOpts() {
1373 LangOptions LangOpts;
1374 LangOpts.CPlusPlus = 1;
1375 LangOpts.CPlusPlus11 = 1;
1376 LangOpts.Bool = 1;
1377 LangOpts.ObjC1 = 1;
1378 LangOpts.ObjC2 = 1;
1379 return LangOpts;
1380}
1381
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001382} // namespace format
1383} // namespace clang