blob: a167834a4ea29d80c3cdd700f24a3998ffcf753f [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,
Daniel Jasper7194e182013-01-10 11:14:08 +000040 TT_ObjCMethodSpecifier,
41 TT_OverloadedOperator,
42 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000043 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_TemplateCloser,
45 TT_TemplateOpener,
46 TT_TrailingUnaryOperator,
47 TT_UnaryOperator,
48 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000049};
50
51enum LineType {
52 LT_Invalid,
53 LT_Other,
54 LT_PreprocessorDirective,
55 LT_VirtualFunctionDecl,
56 LT_ObjCMethodDecl
57};
58
Daniel Jasper7c85fde2013-01-08 14:56:18 +000059class AnnotatedToken {
60public:
61 AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000062 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
63 CanBreakBefore(false), MustBreakBefore(false),
64 ClosesTemplateDeclaration(false), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000065
66 bool is(tok::TokenKind Kind) const {
67 return FormatTok.Tok.is(Kind);
68 }
69 bool isNot(tok::TokenKind Kind) const {
70 return FormatTok.Tok.isNot(Kind);
71 }
72 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
73 return FormatTok.Tok.isObjCAtKeyword(Kind);
74 }
75
76 FormatToken FormatTok;
77
Daniel Jasperf7935112012-12-03 18:12:45 +000078 TokenType Type;
79
Daniel Jasperf7935112012-12-03 18:12:45 +000080 bool SpaceRequiredBefore;
81 bool CanBreakBefore;
82 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000083
84 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000085
86 std::vector<AnnotatedToken> Children;
87 AnnotatedToken *Parent;
Daniel Jasperf7935112012-12-03 18:12:45 +000088};
89
Daniel Jasper7c85fde2013-01-08 14:56:18 +000090static prec::Level getPrecedence(const AnnotatedToken &Tok) {
91 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +000092}
93
Daniel Jasperf7935112012-12-03 18:12:45 +000094using llvm::MutableArrayRef;
95
96FormatStyle getLLVMStyle() {
97 FormatStyle LLVMStyle;
98 LLVMStyle.ColumnLimit = 80;
99 LLVMStyle.MaxEmptyLinesToKeep = 1;
100 LLVMStyle.PointerAndReferenceBindToType = false;
101 LLVMStyle.AccessModifierOffset = -2;
102 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000103 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000104 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 return LLVMStyle;
106}
107
108FormatStyle getGoogleStyle() {
109 FormatStyle GoogleStyle;
110 GoogleStyle.ColumnLimit = 80;
111 GoogleStyle.MaxEmptyLinesToKeep = 1;
112 GoogleStyle.PointerAndReferenceBindToType = true;
113 GoogleStyle.AccessModifierOffset = -1;
114 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000115 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000116 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000117 return GoogleStyle;
118}
119
120struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000121 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000122 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000123 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000124};
125
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000126/// \brief Replaces the whitespace in front of \p Tok. Only call once for
127/// each \c FormatToken.
128static void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
129 unsigned Spaces, const FormatStyle &Style,
130 SourceManager &SourceMgr,
131 tooling::Replacements &Replaces) {
132 Replaces.insert(tooling::Replacement(
133 SourceMgr, Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
134 std::string(NewLines, '\n') + std::string(Spaces, ' ')));
135}
136
137/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
138/// backslashes to escape newlines inside a preprocessor directive.
139///
140/// This function and \c replaceWhitespace have the same behavior if
141/// \c Newlines == 0.
142static void replacePPWhitespace(
143 const AnnotatedToken &Tok, unsigned NewLines, unsigned Spaces,
144 unsigned WhitespaceStartColumn, const FormatStyle &Style,
145 SourceManager &SourceMgr, tooling::Replacements &Replaces) {
146 std::string NewLineText;
147 if (NewLines > 0) {
148 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
149 WhitespaceStartColumn);
150 for (unsigned i = 0; i < NewLines; ++i) {
151 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
152 NewLineText += "\\\n";
153 Offset = 0;
154 }
155 }
156 Replaces.insert(tooling::Replacement(SourceMgr, Tok.FormatTok.WhiteSpaceStart,
157 Tok.FormatTok.WhiteSpaceLength,
158 NewLineText + std::string(Spaces, ' ')));
159}
160
Daniel Jasperf7935112012-12-03 18:12:45 +0000161class UnwrappedLineFormatter {
162public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000163 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
164 const UnwrappedLine &Line, unsigned FirstIndent,
165 bool FitsOnALine, LineType CurrentLineType,
166 const AnnotatedToken &RootToken,
167 tooling::Replacements &Replaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000168 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000169 FirstIndent(FirstIndent), FitsOnALine(FitsOnALine),
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000170 CurrentLineType(CurrentLineType), RootToken(RootToken),
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000171 Replaces(Replaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000172 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000173 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000174 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 }
176
Manuel Klimek1abf7892013-01-04 23:34:14 +0000177 /// \brief Formats an \c UnwrappedLine.
178 ///
179 /// \returns The column after the last token in the last line of the
180 /// \c UnwrappedLine.
181 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000182 // Initialize state dependent on indent.
Daniel Jasperf7935112012-12-03 18:12:45 +0000183 IndentState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000184 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000185 State.NextToken = &RootToken;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000186 State.Indent.push_back(FirstIndent + 4);
187 State.LastSpace.push_back(FirstIndent);
Daniel Jaspere9de2602012-12-06 09:56:08 +0000188 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000189 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000190 State.ForLoopVariablePos = 0;
191 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000192 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000193
194 // The first token has already been indented and thus consumed.
195 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000196
197 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000198 while (State.NextToken != NULL) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000199 if (FitsOnALine) {
200 addTokenToState(false, false, State);
201 } else {
202 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
203 unsigned Break = calcPenalty(State, true, NoBreak);
204 addTokenToState(Break < NoBreak, false, State);
205 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000206 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000207 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000208 }
209
210private:
211 /// \brief The current state when indenting a unwrapped line.
212 ///
213 /// As the indenting tries different combinations this is copied by value.
214 struct IndentState {
215 /// \brief The number of used columns in the current line.
216 unsigned Column;
217
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000218 const AnnotatedToken *NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000219
Daniel Jasper6d822722012-12-24 16:43:00 +0000220 /// \brief The parenthesis level of the first token on the current line.
221 unsigned StartOfLineLevel;
222
Daniel Jasperf7935112012-12-03 18:12:45 +0000223 /// \brief The position to which a specific parenthesis level needs to be
224 /// indented.
225 std::vector<unsigned> Indent;
226
Daniel Jaspere9de2602012-12-06 09:56:08 +0000227 /// \brief The position of the last space on each level.
228 ///
229 /// Used e.g. to break like:
230 /// functionCall(Parameter, otherCall(
231 /// OtherParameter));
Daniel Jasperf7935112012-12-03 18:12:45 +0000232 std::vector<unsigned> LastSpace;
233
Daniel Jaspere9de2602012-12-06 09:56:08 +0000234 /// \brief The position the first "<<" operator encountered on each level.
235 ///
236 /// Used to align "<<" operators. 0 if no such operator has been encountered
237 /// on a level.
238 std::vector<unsigned> FirstLessLess;
239
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000240 /// \brief Whether a newline needs to be inserted before the block's closing
241 /// brace.
242 ///
243 /// We only want to insert a newline before the closing brace if there also
244 /// was a newline after the beginning left brace.
245 std::vector<bool> BreakBeforeClosingBrace;
246
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000247 /// \brief The column of the first variable in a for-loop declaration.
248 ///
249 /// Used to align the second variable if necessary.
250 unsigned ForLoopVariablePos;
251
252 /// \brief \c true if this line contains a continued for-loop section.
253 bool LineContainsContinuedForLoopSection;
254
Daniel Jasperf7935112012-12-03 18:12:45 +0000255 /// \brief Comparison operator to be able to used \c IndentState in \c map.
256 bool operator<(const IndentState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000257 if (Other.NextToken != NextToken)
258 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000259 if (Other.Column != Column)
260 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000261 if (Other.StartOfLineLevel != StartOfLineLevel)
262 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperf7935112012-12-03 18:12:45 +0000263 if (Other.Indent.size() != Indent.size())
264 return Other.Indent.size() > Indent.size();
265 for (int i = 0, e = Indent.size(); i != e; ++i) {
266 if (Other.Indent[i] != Indent[i])
267 return Other.Indent[i] > Indent[i];
268 }
269 if (Other.LastSpace.size() != LastSpace.size())
270 return Other.LastSpace.size() > LastSpace.size();
271 for (int i = 0, e = LastSpace.size(); i != e; ++i) {
272 if (Other.LastSpace[i] != LastSpace[i])
273 return Other.LastSpace[i] > LastSpace[i];
274 }
Daniel Jaspere9de2602012-12-06 09:56:08 +0000275 if (Other.FirstLessLess.size() != FirstLessLess.size())
276 return Other.FirstLessLess.size() > FirstLessLess.size();
277 for (int i = 0, e = FirstLessLess.size(); i != e; ++i) {
278 if (Other.FirstLessLess[i] != FirstLessLess[i])
279 return Other.FirstLessLess[i] > FirstLessLess[i];
280 }
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000281 if (Other.ForLoopVariablePos != ForLoopVariablePos)
282 return Other.ForLoopVariablePos < ForLoopVariablePos;
283 if (Other.LineContainsContinuedForLoopSection !=
284 LineContainsContinuedForLoopSection)
285 return LineContainsContinuedForLoopSection;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000286 if (Other.BreakBeforeClosingBrace != BreakBeforeClosingBrace)
287 return Other.BreakBeforeClosingBrace > BreakBeforeClosingBrace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000288 return false;
289 }
290 };
291
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000292 /// \brief Appends the next token to \p State and updates information
293 /// necessary for indentation.
294 ///
295 /// Puts the token on the current line if \p Newline is \c true and adds a
296 /// line break and necessary indentation otherwise.
297 ///
298 /// If \p DryRun is \c false, also creates and stores the required
299 /// \c Replacement.
300 void addTokenToState(bool Newline, bool DryRun, IndentState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000301 const AnnotatedToken &Current = *State.NextToken;
302 const AnnotatedToken &Previous = *State.NextToken->Parent;
Nico Weber51306d22013-01-10 00:25:19 +0000303 assert(State.Indent.size());
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000304 unsigned ParenLevel = State.Indent.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000305
306 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000307 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000308 if (Current.is(tok::r_brace)) {
309 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000310 } else if (Current.is(tok::string_literal) &&
311 Previous.is(tok::string_literal)) {
312 State.Column = State.Column - Previous.FormatTok.TokenLength;
313 } else if (Current.is(tok::lessless) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000314 State.FirstLessLess[ParenLevel] != 0) {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000315 State.Column = State.FirstLessLess[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000316 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000317 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
318 Current.is(tok::period) || Previous.is(tok::question) ||
319 Previous.Type == TT_ConditionalExpr)) {
320 // Indent and extra 4 spaces after if we know the current expression is
321 // continued. Don't do that on the top level, as we already indent 4
322 // there.
Daniel Jasperf7935112012-12-03 18:12:45 +0000323 State.Column = State.Indent[ParenLevel] + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000324 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000325 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000326 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000327 State.Column = State.Indent[ParenLevel] - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000328 } else {
Daniel Jasperf7935112012-12-03 18:12:45 +0000329 State.Column = State.Indent[ParenLevel];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000330 }
331
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000332 // A line starting with a closing brace is assumed to be correct for the
333 // same level as before the opening brace.
334 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000335
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000336 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000337 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000338
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000339 if (!DryRun) {
340 if (!Line.InPPDirective)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000341 replaceWhitespace(Current.FormatTok, 1, State.Column, Style,
342 SourceMgr, Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000343 else
Daniel Jasper399d24b2013-01-09 07:06:56 +0000344 replacePPWhitespace(Current.FormatTok, 1, State.Column,
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000345 WhitespaceStartColumn, Style, SourceMgr,
346 Replaces);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000347 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000348
Daniel Jasper89058942013-01-09 09:50:48 +0000349 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000350 if (Current.is(tok::colon) && CurrentLineType != LT_ObjCMethodDecl &&
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000351 State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +0000352 State.Indent[ParenLevel] += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000354 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
355 State.ForLoopVariablePos = State.Column -
356 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000357
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000358 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
359 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000360 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000361
Daniel Jasperf7935112012-12-03 18:12:45 +0000362 if (!DryRun)
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000363 replaceWhitespace(Current, 0, Spaces, Style, SourceMgr, Replaces);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000364
Daniel Jasperbcab4302013-01-09 10:40:23 +0000365 // FIXME: Do we need to do this for assignments nested in other
366 // expressions?
367 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000368 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000369 Previous.is(tok::kw_return)))
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000370 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000371 if (Previous.is(tok::l_paren) ||
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000372 Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000373 State.NextToken->Parent->Type == TT_TemplateOpener)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000374 State.Indent[ParenLevel] = State.Column + Spaces;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000375
Daniel Jasper206df732013-01-07 13:08:40 +0000376 // Top-level spaces that are not part of assignments are exempt as that
377 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000378 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000379 if (Spaces > 0 &&
380 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jaspere9de2602012-12-06 09:56:08 +0000381 State.LastSpace[ParenLevel] = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000382 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000383 moveStateToNextToken(State);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000384 if (Newline && Previous.is(tok::l_brace)) {
385 State.BreakBeforeClosingBrace.back() = true;
386 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000387 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000388
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000389 /// \brief Mark the next token as consumed in \p State and modify its stacks
390 /// accordingly.
391 void moveStateToNextToken(IndentState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000392 const AnnotatedToken &Current = *State.NextToken;
Nico Weber51306d22013-01-10 00:25:19 +0000393 assert(State.Indent.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000394 unsigned ParenLevel = State.Indent.size() - 1;
395
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000396 if (Current.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0)
Daniel Jaspere9de2602012-12-06 09:56:08 +0000397 State.FirstLessLess[ParenLevel] = State.Column;
398
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000399 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000400 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000401 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
402 Current.is(tok::l_brace) ||
403 State.NextToken->Type == TT_TemplateOpener) {
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000404 if (Current.is(tok::l_brace)) {
405 // FIXME: This does not work with nested static initializers.
406 // Implement a better handling for static initializers and similar
407 // constructs.
408 State.Indent.push_back(Line.Level * 2 + 2);
409 } else {
410 State.Indent.push_back(4 + State.LastSpace.back());
411 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000412 State.LastSpace.push_back(State.LastSpace.back());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000413 State.FirstLessLess.push_back(0);
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000414 State.BreakBeforeClosingBrace.push_back(false);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000415 }
416
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000417 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000418 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000419 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
420 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
421 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000422 State.Indent.pop_back();
423 State.LastSpace.pop_back();
Daniel Jaspere9de2602012-12-06 09:56:08 +0000424 State.FirstLessLess.pop_back();
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000425 State.BreakBeforeClosingBrace.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000426 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000427
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000428 if (State.NextToken->Children.empty())
429 State.NextToken = NULL;
430 else
431 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000432
433 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000434 }
435
Nico Weber49cbc2c2013-01-07 15:15:29 +0000436 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000437 unsigned splitPenalty(const AnnotatedToken &Tok) {
438 const AnnotatedToken &Left = Tok;
439 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000440
441 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000442 if (RootToken.is(tok::kw_for) &&
443 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000444 return 20;
445
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000446 if (Left.is(tok::semi) || Left.is(tok::comma) ||
447 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000448 return 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000449 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000450 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000451
Daniel Jasper399d24b2013-01-09 07:06:56 +0000452 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
453 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000454 prec::Level Level = getPrecedence(Left);
455
456 // Breaking after an assignment leads to a bad result as the two sides of
457 // the assignment are visually very close together.
458 if (Level == prec::Assignment)
459 return 50;
460
Daniel Jasperde5c2072012-12-24 00:13:23 +0000461 if (Level != prec::Unknown)
462 return Level;
463
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000464 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000465 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000466
Daniel Jasperf7935112012-12-03 18:12:45 +0000467 return 3;
468 }
469
Daniel Jasper2df93312013-01-09 10:16:05 +0000470 unsigned getColumnLimit() {
471 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
472 }
473
Daniel Jasperf7935112012-12-03 18:12:45 +0000474 /// \brief Calculate the number of lines needed to format the remaining part
475 /// of the unwrapped line.
476 ///
477 /// Assumes the formatting so far has led to
478 /// the \c IndentState \p State. If \p NewLine is set, a new line will be
479 /// added after the previous token.
480 ///
481 /// \param StopAt is used for optimization. If we can determine that we'll
482 /// definitely need at least \p StopAt additional lines, we already know of a
483 /// better solution.
484 unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) {
485 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000486 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000487 return 0;
488
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000489 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000490 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000491 if (NewLine && !State.NextToken->CanBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000492 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000493 if (!NewLine && State.NextToken->is(tok::r_brace) &&
494 State.BreakBeforeClosingBrace.back())
495 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000496 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000497 State.LineContainsContinuedForLoopSection)
498 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000499
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000500 unsigned CurrentPenalty = 0;
501 if (NewLine) {
502 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000503 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000504 } else {
505 if (State.Indent.size() < State.StartOfLineLevel)
506 CurrentPenalty += Parameters.PenaltyLevelDecrease *
507 (State.StartOfLineLevel - State.Indent.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000508 }
509
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000510 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000511
Daniel Jasper2df93312013-01-09 10:16:05 +0000512 // Exceeding column limit is bad, assign penalty.
513 if (State.Column > getColumnLimit()) {
514 unsigned ExcessCharacters = State.Column - getColumnLimit();
515 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
516 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000517
Daniel Jasperf7935112012-12-03 18:12:45 +0000518 if (StopAt <= CurrentPenalty)
519 return UINT_MAX;
520 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000521 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000522 if (I != Memory.end()) {
523 // If this state has already been examined, we can safely return the
524 // previous result if we
525 // - have not hit the optimatization (and thus returned UINT_MAX) OR
526 // - are now computing for a smaller or equal StopAt.
527 unsigned SavedResult = I->second.first;
528 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000529 if (SavedResult != UINT_MAX)
530 return SavedResult + CurrentPenalty;
531 else if (StopAt <= SavedStopAt)
532 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000533 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000534
535 unsigned NoBreak = calcPenalty(State, false, StopAt);
536 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
537 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000538
539 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
540 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000541 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000542
543 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000544 }
545
Daniel Jasperf7935112012-12-03 18:12:45 +0000546 FormatStyle Style;
547 SourceManager &SourceMgr;
548 const UnwrappedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000549 const unsigned FirstIndent;
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000550 const bool FitsOnALine;
Daniel Jasperda16db32013-01-07 10:48:50 +0000551 const LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000552 const AnnotatedToken &RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000553 tooling::Replacements &Replaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000554
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000555 // A map from an indent state to a pair (Result, Used-StopAt).
556 typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap;
557 StateMap Memory;
558
Daniel Jasperf7935112012-12-03 18:12:45 +0000559 OptimizationParameters Parameters;
560};
561
562/// \brief Determines extra information about the tokens comprising an
563/// \c UnwrappedLine.
564class TokenAnnotator {
565public:
566 TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style,
Manuel Klimekc74d2922013-01-07 08:54:53 +0000567 SourceManager &SourceMgr, Lexer &Lex)
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000568 : Style(Style), SourceMgr(SourceMgr), Lex(Lex),
569 RootToken(Line.RootToken) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000570 }
571
572 /// \brief A parser that gathers additional information about tokens.
573 ///
574 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
575 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
576 /// into template parameter lists.
577 class AnnotatingParser {
578 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000579 AnnotatingParser(AnnotatedToken &RootToken)
580 : CurrentToken(&RootToken), KeywordVirtualFound(false) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000581 }
582
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000583 bool parseAngle() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000584 while (CurrentToken != NULL) {
585 if (CurrentToken->is(tok::greater)) {
586 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000587 next();
588 return true;
589 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000590 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
591 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000593 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
594 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000595 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000596 if (!consumeToken())
597 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 }
599 return false;
600 }
601
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000602 bool parseParens() {
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000603 if (CurrentToken != NULL && CurrentToken->is(tok::caret))
604 CurrentToken->Parent->Type = TT_ObjCBlockLParen;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000605 while (CurrentToken != NULL) {
606 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 next();
608 return true;
609 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000610 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000612 if (!consumeToken())
613 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000614 }
615 return false;
616 }
617
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000618 bool parseSquare() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 while (CurrentToken != NULL) {
620 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000621 next();
622 return true;
623 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000624 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000625 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000626 if (!consumeToken())
627 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000628 }
629 return false;
630 }
631
Daniel Jasper83a54d22013-01-10 09:26:47 +0000632 bool parseBrace() {
633 while (CurrentToken != NULL) {
634 if (CurrentToken->is(tok::r_brace)) {
635 next();
636 return true;
637 }
638 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
639 return false;
640 if (!consumeToken())
641 return false;
642 }
643 // Lines can currently end with '{'.
644 return true;
645 }
646
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000647 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000648 while (CurrentToken != NULL) {
649 if (CurrentToken->is(tok::colon)) {
650 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000651 next();
652 return true;
653 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000654 if (!consumeToken())
655 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000656 }
657 return false;
658 }
659
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000660 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000661 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
662 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000663 next();
664 if (!parseAngle())
665 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000666 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000667 parseLine();
668 return true;
669 }
670 return false;
671 }
672
Daniel Jasperc0880a92013-01-04 18:52:56 +0000673 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000674 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000675 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000676 switch (Tok->FormatTok.Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000677 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000678 if (!parseParens())
679 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 if (CurrentToken != NULL && CurrentToken->is(tok::colon)) {
681 CurrentToken->Type = TT_CtorInitializerColon;
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000682 next();
683 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 break;
685 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +0000686 if (!parseSquare())
687 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000688 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000689 case tok::l_brace:
690 if (!parseBrace())
691 return false;
692 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000693 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000694 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000695 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +0000696 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000697 Tok->Type = TT_BinaryOperator;
698 CurrentToken = Tok;
699 next();
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 }
701 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000702 case tok::r_paren:
703 case tok::r_square:
704 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000705 case tok::r_brace:
706 // Lines can start with '}'.
707 if (Tok->Parent != NULL)
708 return false;
709 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000711 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000712 break;
713 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000714 if (CurrentToken->is(tok::l_paren)) {
715 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000716 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000717 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
718 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000719 next();
720 }
721 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000722 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
723 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +0000724 next();
725 }
726 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000727 break;
728 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000729 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +0000730 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000731 case tok::kw_template:
732 parseTemplateDeclaration();
733 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000734 default:
735 break;
736 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000737 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 }
739
Daniel Jasper050948a52012-12-21 17:58:39 +0000740 void parseIncludeDirective() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000741 while (CurrentToken != NULL) {
742 if (CurrentToken->is(tok::slash))
743 CurrentToken->Type = TT_DirectorySeparator;
744 else if (CurrentToken->is(tok::less))
745 CurrentToken->Type = TT_TemplateOpener;
746 else if (CurrentToken->is(tok::greater))
747 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasper050948a52012-12-21 17:58:39 +0000748 next();
749 }
750 }
751
752 void parsePreprocessorDirective() {
753 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000754 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +0000755 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000756 // Hashes in the middle of a line can lead to any strange token
757 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000758 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +0000759 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000760 switch (
761 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000762 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +0000763 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +0000764 parseIncludeDirective();
765 break;
766 default:
767 break;
768 }
769 }
770
Daniel Jasperda16db32013-01-07 10:48:50 +0000771 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000772 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000773 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +0000774 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +0000775 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 while (CurrentToken != NULL) {
777 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +0000778 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000779 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +0000780 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000782 if (KeywordVirtualFound)
783 return LT_VirtualFunctionDecl;
784 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 }
786
787 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000788 if (CurrentToken != NULL && !CurrentToken->Children.empty())
789 CurrentToken = &CurrentToken->Children[0];
790 else
791 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +0000792 }
793
794 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000795 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +0000796 bool KeywordVirtualFound;
Daniel Jasperf7935112012-12-03 18:12:45 +0000797 };
798
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000799 void createAnnotatedTokens(AnnotatedToken &Current) {
800 if (!Current.FormatTok.Children.empty()) {
801 Current.Children.push_back(AnnotatedToken(Current.FormatTok.Children[0]));
802 Current.Children.back().Parent = &Current;
803 createAnnotatedTokens(Current.Children.back());
804 }
805 }
Daniel Jasperda16db32013-01-07 10:48:50 +0000806
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000807 void calculateExtraInformation(AnnotatedToken &Current) {
808 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
809
Manuel Klimek52b15152013-01-09 15:25:02 +0000810 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000811 Current.MustBreakBefore = true;
812 } else {
Manuel Klimek52b15152013-01-09 15:25:02 +0000813 if (Current.Type == TT_CtorInitializerColon || Current.Parent->Type ==
814 TT_LineComment || (Current.is(tok::string_literal) &&
815 Current.Parent->is(tok::string_literal))) {
816 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +0000817 } else {
818 Current.MustBreakBefore = false;
819 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000820 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000821 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000822 if (!Current.Children.empty())
823 calculateExtraInformation(Current.Children[0]);
824 }
825
826 bool annotate() {
827 createAnnotatedTokens(RootToken);
828
829 AnnotatingParser Parser(RootToken);
Daniel Jasperda16db32013-01-07 10:48:50 +0000830 CurrentLineType = Parser.parseLine();
831 if (CurrentLineType == LT_Invalid)
Daniel Jasperc0880a92013-01-04 18:52:56 +0000832 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000833
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000834 determineTokenTypes(RootToken, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +0000835
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000836 if (RootToken.Type == TT_ObjCMethodSpecifier)
Daniel Jasperda16db32013-01-07 10:48:50 +0000837 CurrentLineType = LT_ObjCMethodDecl;
838
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 if (!RootToken.Children.empty())
840 calculateExtraInformation(RootToken.Children[0]);
Daniel Jasperc0880a92013-01-04 18:52:56 +0000841 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000842 }
843
Daniel Jasperda16db32013-01-07 10:48:50 +0000844 LineType getLineType() {
845 return CurrentLineType;
846 }
847
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000848 const AnnotatedToken &getRootToken() {
849 return RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000850 }
851
852private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000853 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
854 if (getPrecedence(Current) == prec::Assignment ||
855 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
856 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000857
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000858 if (Current.Type == TT_Unknown) {
859 if (Current.is(tok::star) || Current.is(tok::amp)) {
860 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000861 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
862 Current.is(tok::caret)) {
863 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
865 Current.Type = determineIncrementUsage(Current);
866 } else if (Current.is(tok::exclaim)) {
867 Current.Type = TT_UnaryOperator;
868 } else if (isBinaryOperator(Current)) {
869 Current.Type = TT_BinaryOperator;
870 } else if (Current.is(tok::comment)) {
871 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
872 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +0000873 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +0000877 } else if (Current.is(tok::r_paren) &&
878 (Current.Parent->Type == TT_PointerOrReference ||
879 Current.Parent->Type == TT_TemplateCloser)) {
880 // FIXME: We need to get smarter and understand more cases of casts.
881 Current.Type = TT_CastRParen;
Daniel Jasperf7935112012-12-03 18:12:45 +0000882 }
883 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000884
885 if (!Current.Children.empty())
886 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +0000887 }
888
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000889 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +0000890 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000891 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +0000892 }
893
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000894 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
895 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000896 return TT_UnaryOperator;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000897 if (Tok.Children.size() == 0)
Daniel Jasperda16db32013-01-07 10:48:50 +0000898 return TT_Unknown;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000899 const FormatToken &PrevToken = Tok.Parent->FormatTok;
900 const FormatToken &NextToken = Tok.Children[0].FormatTok;
Daniel Jasperf7935112012-12-03 18:12:45 +0000901
Daniel Jasper3c2557d2013-01-04 20:46:38 +0000902 if (PrevToken.Tok.is(tok::l_paren) || PrevToken.Tok.is(tok::l_square) ||
903 PrevToken.Tok.is(tok::comma) || PrevToken.Tok.is(tok::kw_return) ||
Daniel Jasper7194e182013-01-10 11:14:08 +0000904 PrevToken.Tok.is(tok::colon) || Tok.Parent->Type == TT_BinaryOperator ||
905 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +0000906 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000907
Daniel Jasper542de162013-01-02 15:46:59 +0000908 if (PrevToken.Tok.isLiteral() || NextToken.Tok.isLiteral() ||
Daniel Jasper3c0431c2013-01-02 17:21:36 +0000909 NextToken.Tok.is(tok::plus) || NextToken.Tok.is(tok::minus) ||
910 NextToken.Tok.is(tok::plusplus) || NextToken.Tok.is(tok::minusminus) ||
911 NextToken.Tok.is(tok::tilde) || NextToken.Tok.is(tok::exclaim) ||
912 NextToken.Tok.is(tok::kw_alignof) || NextToken.Tok.is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +0000913 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000914
Daniel Jasper542de162013-01-02 15:46:59 +0000915 if (NextToken.Tok.is(tok::comma) || NextToken.Tok.is(tok::r_paren) ||
916 NextToken.Tok.is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +0000917 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +0000918
Daniel Jasper426702d2012-12-05 07:51:39 +0000919 // It is very unlikely that we are going to find a pointer or reference type
920 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +0000921 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +0000922 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +0000923
Daniel Jasperda16db32013-01-07 10:48:50 +0000924 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +0000925 }
926
Daniel Jasperfb3f2482013-01-09 08:36:49 +0000927 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper8dd40472012-12-21 09:41:31 +0000928 // At the start of the line, +/- specific ObjectiveC method declarations.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000929 if (Tok.Parent == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +0000930 return TT_ObjCMethodSpecifier;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000931
932 // Use heuristics to recognize unary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000933 if (Tok.Parent->is(tok::equal) || Tok.Parent->is(tok::l_paren) ||
934 Tok.Parent->is(tok::comma) || Tok.Parent->is(tok::l_square) ||
935 Tok.Parent->is(tok::question) || Tok.Parent->is(tok::colon) ||
936 Tok.Parent->is(tok::kw_return) || Tok.Parent->is(tok::kw_case))
Daniel Jasperda16db32013-01-07 10:48:50 +0000937 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000938
939 // There can't be to consecutive binary operators.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000940 if (Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +0000941 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000942
943 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +0000944 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000945 }
946
947 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
949 if (Tok.Parent != NULL && Tok.Parent->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +0000950 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +0000951
Daniel Jasperda16db32013-01-07 10:48:50 +0000952 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +0000953 }
954
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000955 bool spaceRequiredBetween(const AnnotatedToken &Left,
956 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +0000957 if (Right.is(tok::hashhash))
958 return Left.is(tok::hash);
959 if (Left.is(tok::hashhash) || Left.is(tok::hash))
960 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +0000961 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
962 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000963 if (Left.is(tok::kw_template) && Right.is(tok::less))
964 return true;
965 if (Left.is(tok::arrow) || Right.is(tok::arrow))
966 return false;
967 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
968 return false;
Nico Weber77aa2502013-01-08 19:40:21 +0000969 if (Left.is(tok::at) &&
970 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
971 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +0000972 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
973 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +0000974 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000975 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
976 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000977 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000978 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +0000979 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
980 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000982 return Right.FormatTok.Tok.isLiteral() ||
983 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 if (Right.is(tok::star) && Left.is(tok::l_paren))
985 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000986 if (Left.is(tok::l_square) || Right.is(tok::l_square) ||
987 Right.is(tok::r_square))
988 return false;
Daniel Jasper27234032012-12-07 09:52:15 +0000989 if (Left.is(tok::coloncolon) ||
990 (Right.is(tok::coloncolon) &&
991 (Left.is(tok::identifier) || Left.is(tok::greater))))
Daniel Jasperf7935112012-12-03 18:12:45 +0000992 return false;
993 if (Left.is(tok::period) || Right.is(tok::period))
994 return false;
995 if (Left.is(tok::colon) || Right.is(tok::colon))
996 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000997 if (Left.is(tok::l_paren))
998 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000999 if (Right.is(tok::l_paren)) {
Daniel Jasper8dd40472012-12-21 09:41:31 +00001000 return Left.is(tok::kw_if) || Left.is(tok::kw_for) ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001001 Left.is(tok::kw_while) || Left.is(tok::kw_switch) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001002 Left.is(tok::kw_return) || Left.is(tok::kw_catch);
Daniel Jasperf7935112012-12-03 18:12:45 +00001003 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001004 if (Left.is(tok::at) &&
1005 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001006 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001007 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1008 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001009 return true;
1010 }
1011
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001012 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001013 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001014 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1015 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001016 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001017 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001018 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001020 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001021 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001022 // Don't space between ')' and <id>
1023 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001024 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001025 // Don't space between ':' and '('
1026 return false;
1027 }
1028
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001029 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001030 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 if (Tok.Type == TT_OverloadedOperator)
1032 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001033 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001034 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001035 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001036 if (Tok.is(tok::colon))
1037 return RootToken.isNot(tok::kw_case) && (!Tok.Children.empty());
Daniel Jasper7194e182013-01-10 11:14:08 +00001038 if (Tok.Parent->Type == TT_UnaryOperator ||
1039 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001040 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001041 if (Tok.Type == TT_UnaryOperator)
1042 return Tok.Parent->isNot(tok::l_paren) &&
1043 Tok.Parent->isNot(tok::l_square);
1044 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1045 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001046 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1047 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001048 if (Tok.Type == TT_DirectorySeparator ||
1049 Tok.Parent->Type == TT_DirectorySeparator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001050 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001051 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001052 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001054 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001055 if (Tok.is(tok::less) && RootToken.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001056 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001057 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001058 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001059 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001060 }
1061
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001062 bool canBreakBefore(const AnnotatedToken &Right) {
1063 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001064 if (CurrentLineType == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001065 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1066 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001067 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 if (CurrentLineType == LT_ObjCMethodDecl && Right.is(tok::identifier) &&
1069 Left.is(tok::l_paren) && Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001070 // Don't break this identifier as ':' or identifier
1071 // before it will break.
1072 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001073 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1074 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001075 // Don't break at ':' if identifier before it can beak.
1076 return false;
1077 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001079 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001080 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001081 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001082 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001083 if (Left.is(tok::equal) && CurrentLineType == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001084 return false;
1085
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001086 if (Right.is(tok::comment))
1087 return !Right.Children.empty();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001088 if (Right.is(tok::r_paren) || Right.is(tok::l_brace) ||
Daniel Jasperd8bb2db2013-01-09 09:33:39 +00001089 Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001090 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001091 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1092 Left.is(tok::comma) || Right.is(tok::lessless) ||
1093 Right.is(tok::arrow) || Right.is(tok::period) ||
1094 Right.is(tok::colon) || Left.is(tok::semi) ||
Daniel Jasper399d24b2013-01-09 07:06:56 +00001095 Left.is(tok::l_brace) || Left.is(tok::question) ||
Manuel Klimek0ddd57a2013-01-10 15:58:26 +00001096 Right.is(tok::r_brace) || Left.Type == TT_ConditionalExpr ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001097 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001098 }
1099
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 FormatStyle Style;
1101 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001102 Lexer &Lex;
Daniel Jasperda16db32013-01-07 10:48:50 +00001103 LineType CurrentLineType;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001104 AnnotatedToken RootToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001105};
1106
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001107class LexerBasedFormatTokenSource : public FormatTokenSource {
1108public:
1109 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001110 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001111 IdentTable(Lex.getLangOpts()) {
1112 Lex.SetKeepWhitespaceMode(true);
1113 }
1114
1115 virtual FormatToken getNextToken() {
1116 if (GreaterStashed) {
1117 FormatTok.NewlinesBefore = 0;
1118 FormatTok.WhiteSpaceStart =
1119 FormatTok.Tok.getLocation().getLocWithOffset(1);
1120 FormatTok.WhiteSpaceLength = 0;
1121 GreaterStashed = false;
1122 return FormatTok;
1123 }
1124
1125 FormatTok = FormatToken();
1126 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001127 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001128 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001129 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1130 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001131
1132 // Consume and record whitespace until we find a significant token.
1133 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001134 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001135 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1136 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001137 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1138
1139 if (FormatTok.Tok.is(tok::eof))
1140 return FormatTok;
1141 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001142 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001143 }
Manuel Klimekef920692013-01-07 07:56:50 +00001144
1145 // Now FormatTok is the next non-whitespace token.
1146 FormatTok.TokenLength = Text.size();
1147
Manuel Klimek1abf7892013-01-04 23:34:14 +00001148 // In case the token starts with escaped newlines, we want to
1149 // take them into account as whitespace - this pattern is quite frequent
1150 // in macro definitions.
1151 // FIXME: What do we want to do with other escaped spaces, and escaped
1152 // spaces or newlines in the middle of tokens?
1153 // FIXME: Add a more explicit test.
1154 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001155 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001156 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001157 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001158 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001159 }
1160
1161 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001162 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001163 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001164 FormatTok.Tok.setKind(Info.getTokenID());
1165 }
1166
1167 if (FormatTok.Tok.is(tok::greatergreater)) {
1168 FormatTok.Tok.setKind(tok::greater);
1169 GreaterStashed = true;
1170 }
1171
1172 return FormatTok;
1173 }
1174
1175private:
1176 FormatToken FormatTok;
1177 bool GreaterStashed;
1178 Lexer &Lex;
1179 SourceManager &SourceMgr;
1180 IdentifierTable IdentTable;
1181
1182 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001183 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001184 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1185 Tok.getLength());
1186 }
1187};
1188
Daniel Jasperf7935112012-12-03 18:12:45 +00001189class Formatter : public UnwrappedLineConsumer {
1190public:
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001191 Formatter(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
1192 Lexer &Lex, SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001193 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001194 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001195 Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001196
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001197 virtual ~Formatter() {
1198 }
1199
Daniel Jasperf7935112012-12-03 18:12:45 +00001200 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001201 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001202 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001203 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001204 unsigned PreviousEndOfLineColumn = 0;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001205 for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),
1206 E = UnwrappedLines.end();
1207 I != E; ++I)
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001208 PreviousEndOfLineColumn = formatUnwrappedLine(*I,
1209 PreviousEndOfLineColumn);
Daniel Jasperf7935112012-12-03 18:12:45 +00001210 return Replaces;
1211 }
1212
1213private:
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +00001214 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001215 UnwrappedLines.push_back(TheLine);
1216 }
1217
Manuel Klimek1abf7892013-01-04 23:34:14 +00001218 unsigned formatUnwrappedLine(const UnwrappedLine &TheLine,
1219 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001220 const FormatToken *First = &TheLine.RootToken;
1221 const FormatToken *Last = First;
1222 while (!Last->Children.empty())
1223 Last = &Last->Children.back();
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001224 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001225 First->Tok.getLocation(),
1226 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001227
1228 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1229 if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1230 Ranges[i].getBegin()) ||
1231 SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1232 LineRange.getBegin()))
1233 continue;
1234
Manuel Klimekc74d2922013-01-07 08:54:53 +00001235 TokenAnnotator Annotator(TheLine, Style, SourceMgr, Lex);
Daniel Jasperc0880a92013-01-04 18:52:56 +00001236 if (!Annotator.annotate())
Manuel Klimek1abf7892013-01-04 23:34:14 +00001237 break;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001238 unsigned Indent = formatFirstToken(Annotator.getRootToken(),
1239 TheLine.Level, TheLine.InPPDirective,
1240 PreviousEndOfLineColumn);
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +00001241 bool FitsOnALine = fitsOnALine(Annotator.getRootToken(), Indent,
1242 TheLine.InPPDirective);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001243 UnwrappedLineFormatter Formatter(
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +00001244 Style, SourceMgr, TheLine, Indent, FitsOnALine,
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001245 Annotator.getLineType(), Annotator.getRootToken(), Replaces,
Daniel Jasperda16db32013-01-07 10:48:50 +00001246 StructuralError);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001247 return Formatter.format();
Daniel Jasperf7935112012-12-03 18:12:45 +00001248 }
Manuel Klimek1abf7892013-01-04 23:34:14 +00001249 // If we did not reformat this unwrapped line, the column at the end of the
1250 // last token is unchanged - thus, we can calculate the end of the last
1251 // token, and return the result.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001252 return SourceMgr.getSpellingColumnNumber(Last->Tok.getLocation()) +
1253 Lex.MeasureTokenLength(Last->Tok.getLocation(), SourceMgr,
Manuel Klimek1abf7892013-01-04 23:34:14 +00001254 Lex.getLangOpts()) -
1255 1;
Daniel Jasperf7935112012-12-03 18:12:45 +00001256 }
1257
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +00001258 bool fitsOnALine(const AnnotatedToken &RootToken, unsigned Indent,
1259 bool InPPDirective) {
1260 // Check whether the UnwrappedLine can be put onto a single line. If so,
1261 // this is bound to be the optimal solution (by definition) and we don't
1262 // need to analyze the entire solution space.
1263 unsigned Columns = Indent + RootToken.FormatTok.TokenLength;
1264 bool FitsOnALine = true;
1265 const AnnotatedToken *Tok = &RootToken;
1266 while (Tok != NULL) {
1267 Columns += (Tok->SpaceRequiredBefore ? 1 : 0) +
1268 Tok->FormatTok.TokenLength;
1269 // A special case for the colon of a constructor initializer as this only
1270 // needs to be put on a new line if the line needs to be split.
1271 if (Columns > Style.ColumnLimit - (InPPDirective ? 1 : 0) ||
1272 (Tok->MustBreakBefore && Tok->Type != TT_CtorInitializerColon)) {
1273 FitsOnALine = false;
1274 break;
1275 }
1276 Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
1277 }
1278 return FitsOnALine;
1279 }
1280
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001281 /// \brief Add a new line and the required indent before the first Token
1282 /// of the \c UnwrappedLine if there was no structural parsing error.
1283 /// Returns the indent level of the \c UnwrappedLine.
1284 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1285 bool InPPDirective,
1286 unsigned PreviousEndOfLineColumn) {
1287 const FormatToken& Tok = RootToken.FormatTok;
1288 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1289 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1290
1291 unsigned Newlines = std::min(Tok.NewlinesBefore,
1292 Style.MaxEmptyLinesToKeep + 1);
1293 if (Newlines == 0 && !Tok.IsFirst)
1294 Newlines = 1;
1295 unsigned Indent = Level * 2;
1296
1297 bool IsAccessModifier = false;
1298 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1299 RootToken.is(tok::kw_private))
1300 IsAccessModifier = true;
1301 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1302 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1303 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1304 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1305 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1306 IsAccessModifier = true;
1307
1308 if (IsAccessModifier &&
1309 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1310 Indent += Style.AccessModifierOffset;
1311 if (!InPPDirective || Tok.HasUnescapedNewline) {
1312 replaceWhitespace(Tok, Newlines, Indent, Style, SourceMgr, Replaces);
1313 } else {
1314 replacePPWhitespace(Tok, Newlines, Indent, PreviousEndOfLineColumn, Style,
1315 SourceMgr, Replaces);
1316 }
1317 return Indent;
1318 }
1319
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001320 clang::DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001321 FormatStyle Style;
1322 Lexer &Lex;
1323 SourceManager &SourceMgr;
1324 tooling::Replacements Replaces;
1325 std::vector<CharSourceRange> Ranges;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001326 std::vector<UnwrappedLine> UnwrappedLines;
1327 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001328};
1329
1330tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1331 SourceManager &SourceMgr,
1332 std::vector<CharSourceRange> Ranges) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001333 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1334 TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
1335 DiagnosticPrinter.BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1336 DiagnosticsEngine Diagnostics(
1337 llvm::IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
1338 &DiagnosticPrinter, false);
1339 Diagnostics.setSourceManager(&SourceMgr);
1340 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001341 return formatter.format();
1342}
1343
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001344LangOptions getFormattingLangOpts() {
1345 LangOptions LangOpts;
1346 LangOpts.CPlusPlus = 1;
1347 LangOpts.CPlusPlus11 = 1;
1348 LangOpts.Bool = 1;
1349 LangOpts.ObjC1 = 1;
1350 LangOpts.ObjC2 = 1;
1351 return LangOpts;
1352}
1353
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001354} // namespace format
1355} // namespace clang