blob: 8eebda0740b97b57b839058ce587a25cb67fbed7 [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
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasperd2639ef2013-01-28 15:16:31 +000053 TT_RangeBasedForLoopColon,
54 TT_StartOfName,
Daniel Jasper7194e182013-01-10 11:14:08 +000055 TT_TemplateCloser,
56 TT_TemplateOpener,
57 TT_TrailingUnaryOperator,
58 TT_UnaryOperator,
59 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000060};
61
62enum LineType {
63 LT_Invalid,
64 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000065 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000066 LT_PreprocessorDirective,
67 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000068 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000069 LT_ObjCMethodDecl,
70 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000071};
72
Daniel Jasper7c85fde2013-01-08 14:56:18 +000073class AnnotatedToken {
74public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000075 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000076 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
77 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000078 ClosesTemplateDeclaration(false), MatchingParen(NULL),
79 ParameterCount(1), Parent(NULL) {
80 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000081
Daniel Jasper25837aa2013-01-14 14:14:23 +000082 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
83 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
84
Daniel Jasper7c85fde2013-01-08 14:56:18 +000085 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
86 return FormatTok.Tok.isObjCAtKeyword(Kind);
87 }
88
89 FormatToken FormatTok;
90
Daniel Jasperf7935112012-12-03 18:12:45 +000091 TokenType Type;
92
Daniel Jasperf7935112012-12-03 18:12:45 +000093 bool SpaceRequiredBefore;
94 bool CanBreakBefore;
95 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000096
97 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000098
Daniel Jasper9278eb92013-01-16 14:59:02 +000099 AnnotatedToken *MatchingParen;
100
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000101 /// \brief Number of parameters, if this is "(", "[" or "<".
102 ///
103 /// This is initialized to 1 as we don't need to distinguish functions with
104 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
105 /// the number of commas.
106 unsigned ParameterCount;
107
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000108 /// \brief The total length of the line up to and including this token.
109 unsigned TotalLength;
110
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000111 std::vector<AnnotatedToken> Children;
112 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000113
114 const AnnotatedToken *getPreviousNoneComment() const {
115 AnnotatedToken *Tok = Parent;
116 while (Tok != NULL && Tok->is(tok::comment))
117 Tok = Tok->Parent;
118 return Tok;
119 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000120};
121
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000122class AnnotatedLine {
123public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000124 AnnotatedLine(const UnwrappedLine &Line)
125 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000126 InPPDirective(Line.InPPDirective),
127 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000128 assert(!Line.Tokens.empty());
129 AnnotatedToken *Current = &First;
130 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
131 E = Line.Tokens.end();
132 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000133 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000134 Current->Children[0].Parent = Current;
135 Current = &Current->Children[0];
136 }
137 Last = Current;
138 }
139 AnnotatedLine(const AnnotatedLine &Other)
140 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000141 InPPDirective(Other.InPPDirective),
142 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000143 Last = &First;
144 while (!Last->Children.empty()) {
145 Last->Children[0].Parent = Last;
146 Last = &Last->Children[0];
147 }
148 }
149
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000150 AnnotatedToken First;
151 AnnotatedToken *Last;
152
153 LineType Type;
154 unsigned Level;
155 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000156 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000157};
158
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000159static prec::Level getPrecedence(const AnnotatedToken &Tok) {
160 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000161}
162
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000163bool isBinaryOperator(const AnnotatedToken &Tok) {
164 // Comma is a binary operator, but does not behave as such wrt. formatting.
165 return getPrecedence(Tok) > prec::Comma;
166}
167
Daniel Jasperf7935112012-12-03 18:12:45 +0000168FormatStyle getLLVMStyle() {
169 FormatStyle LLVMStyle;
170 LLVMStyle.ColumnLimit = 80;
171 LLVMStyle.MaxEmptyLinesToKeep = 1;
172 LLVMStyle.PointerAndReferenceBindToType = false;
173 LLVMStyle.AccessModifierOffset = -2;
174 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000175 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000176 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000177 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000178 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +0000179 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000180 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000181 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000182 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000183 return LLVMStyle;
184}
185
186FormatStyle getGoogleStyle() {
187 FormatStyle GoogleStyle;
188 GoogleStyle.ColumnLimit = 80;
189 GoogleStyle.MaxEmptyLinesToKeep = 1;
190 GoogleStyle.PointerAndReferenceBindToType = true;
191 GoogleStyle.AccessModifierOffset = -1;
192 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000193 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000194 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000195 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000196 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +0000197 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000198 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000199 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000200 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000201 return GoogleStyle;
202}
203
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000204FormatStyle getChromiumStyle() {
205 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000206 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000207 return ChromiumStyle;
208}
209
Daniel Jasperf7935112012-12-03 18:12:45 +0000210struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000211 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +0000212 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000213};
214
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000215/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000216///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000217/// This includes special handling for certain constructs, e.g. the alignment of
218/// trailing line comments.
219class WhitespaceManager {
220public:
221 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
222
223 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
224 /// each \c AnnotatedToken.
225 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
226 unsigned Spaces, unsigned WhitespaceStartColumn,
227 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000228 // 2+ newlines mean an empty line separating logic scopes.
229 if (NewLines >= 2)
230 alignComments();
231
232 // Align line comments if they are trailing or if they continue other
233 // trailing comments.
234 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000235 (Tok.Parent != NULL || !Comments.empty())) {
236 if (Style.ColumnLimit >=
237 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
238 Comments.push_back(StoredComment());
239 Comments.back().Tok = Tok.FormatTok;
240 Comments.back().Spaces = Spaces;
241 Comments.back().NewLines = NewLines;
242 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
243 Comments.back().MaxColumn = Style.ColumnLimit -
244 Spaces - Tok.FormatTok.TokenLength;
245 return;
246 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000247 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000248
249 // If this line does not have a trailing comment, align the stored comments.
250 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
251 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000252 storeReplacement(Tok.FormatTok,
253 std::string(NewLines, '\n') + std::string(Spaces, ' '));
254 }
255
256 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
257 /// backslashes to escape newlines inside a preprocessor directive.
258 ///
259 /// This function and \c replaceWhitespace have the same behavior if
260 /// \c Newlines == 0.
261 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
262 unsigned Spaces, unsigned WhitespaceStartColumn,
263 const FormatStyle &Style) {
264 std::string NewLineText;
265 if (NewLines > 0) {
266 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
267 WhitespaceStartColumn);
268 for (unsigned i = 0; i < NewLines; ++i) {
269 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
270 NewLineText += "\\\n";
271 Offset = 0;
272 }
273 }
274 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
275 }
276
277 /// \brief Returns all the \c Replacements created during formatting.
278 const tooling::Replacements &generateReplacements() {
279 alignComments();
280 return Replaces;
281 }
282
283private:
284 /// \brief Structure to store a comment for later layout and alignment.
285 struct StoredComment {
286 FormatToken Tok;
287 unsigned MinColumn;
288 unsigned MaxColumn;
289 unsigned NewLines;
290 unsigned Spaces;
291 };
292 SmallVector<StoredComment, 16> Comments;
293 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
294
295 /// \brief Try to align all stashed comments.
296 void alignComments() {
297 unsigned MinColumn = 0;
298 unsigned MaxColumn = UINT_MAX;
299 comment_iterator Start = Comments.begin();
300 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
301 ++I) {
302 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
303 alignComments(Start, I, MinColumn);
304 MinColumn = I->MinColumn;
305 MaxColumn = I->MaxColumn;
306 Start = I;
307 } else {
308 MinColumn = std::max(MinColumn, I->MinColumn);
309 MaxColumn = std::min(MaxColumn, I->MaxColumn);
310 }
311 }
312 alignComments(Start, Comments.end(), MinColumn);
313 Comments.clear();
314 }
315
316 /// \brief Put all the comments between \p I and \p E into \p Column.
317 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
318 while (I != E) {
319 unsigned Spaces = I->Spaces + Column - I->MinColumn;
320 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
321 std::string(Spaces, ' '));
322 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000323 }
324 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000325
326 /// \brief Stores \p Text as the replacement for the whitespace in front of
327 /// \p Tok.
328 void storeReplacement(const FormatToken &Tok, const std::string Text) {
329 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
330 Tok.WhiteSpaceLength, Text));
331 }
332
333 SourceManager &SourceMgr;
334 tooling::Replacements Replaces;
335};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000336
Nico Weberc9d73612013-01-12 22:48:47 +0000337/// \brief Returns if a token is an Objective-C selector name.
338///
Nico Weber92c05392013-01-12 22:51:13 +0000339/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000340static bool isObjCSelectorName(const AnnotatedToken &Tok) {
341 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
342 Tok.Children[0].is(tok::colon) &&
343 Tok.Children[0].Type == TT_ObjCMethodExpr;
344}
345
Daniel Jasperf7935112012-12-03 18:12:45 +0000346class UnwrappedLineFormatter {
347public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000348 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000349 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000350 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000351 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000352 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000353 FirstIndent(FirstIndent), RootToken(RootToken),
354 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000355 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000356 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000357 }
358
Manuel Klimek1abf7892013-01-04 23:34:14 +0000359 /// \brief Formats an \c UnwrappedLine.
360 ///
361 /// \returns The column after the last token in the last line of the
362 /// \c UnwrappedLine.
363 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000364 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000365 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000366 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000367 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000368 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000369 State.ForLoopVariablePos = 0;
370 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000371
Manuel Klimek24998102013-01-16 14:55:28 +0000372 DEBUG({
373 DebugTokenState(*State.NextToken);
374 });
375
Daniel Jaspere9de2602012-12-06 09:56:08 +0000376 // The first token has already been indented and thus consumed.
377 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000378
379 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000380 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000381 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
382 // Calculating the column is important for aligning trailing comments.
383 // FIXME: This does not seem to happen in conjunction with escaped
384 // newlines. If it does, fix!
385 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
386 State.NextToken->FormatTok.TokenLength;
387 State.NextToken = State.NextToken->Children.empty() ? NULL :
388 &State.NextToken->Children[0];
389 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000390 addTokenToState(false, false, State);
391 } else {
392 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
393 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000394 DEBUG({
395 if (Break < NoBreak)
396 llvm::errs() << "\n";
397 else
398 llvm::errs() << " ";
399 llvm::errs() << "<";
400 DebugPenalty(Break, Break < NoBreak);
401 llvm::errs() << "/";
402 DebugPenalty(NoBreak, !(Break < NoBreak));
403 llvm::errs() << "> ";
404 DebugTokenState(*State.NextToken);
405 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000406 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000407 if (State.NextToken != NULL &&
408 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
409 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000410 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000411 State.Stack.back().BreakAfterComma = true;
412 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000413 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000414 }
Manuel Klimek24998102013-01-16 14:55:28 +0000415 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000416 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000417 }
418
419private:
Manuel Klimek24998102013-01-16 14:55:28 +0000420 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
421 const Token &Tok = AnnotatedTok.FormatTok.Tok;
422 llvm::errs()
423 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
424 Tok.getLength());
425 llvm::errs();
426 }
427
428 void DebugPenalty(unsigned Penalty, bool Winner) {
429 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
430 if (Penalty == UINT_MAX)
431 llvm::errs() << "MAX";
432 else
433 llvm::errs() << Penalty;
434 llvm::errs().resetColor();
435 }
436
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000438 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000439 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000440 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jaspera836b902013-01-23 16:58:21 +0000441 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000442
Daniel Jasperf7935112012-12-03 18:12:45 +0000443 /// \brief The position to which a specific parenthesis level needs to be
444 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000446
Daniel Jaspere9de2602012-12-06 09:56:08 +0000447 /// \brief The position of the last space on each level.
448 ///
449 /// Used e.g. to break like:
450 /// functionCall(Parameter, otherCall(
451 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000452 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000453
Daniel Jaspera836b902013-01-23 16:58:21 +0000454 /// \brief This is the column of the first token after an assignment.
455 unsigned AssignmentColumn;
456
Daniel Jaspere9de2602012-12-06 09:56:08 +0000457 /// \brief The position the first "<<" operator encountered on each level.
458 ///
459 /// Used to align "<<" operators. 0 if no such operator has been encountered
460 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000461 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000462
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000463 /// \brief Whether a newline needs to be inserted before the block's closing
464 /// brace.
465 ///
466 /// We only want to insert a newline before the closing brace if there also
467 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000468 bool BreakBeforeClosingBrace;
469
Daniel Jasperca6623b2013-01-28 12:45:14 +0000470 /// \brief The column of a \c ? in a conditional expression;
471 unsigned QuestionColumn;
472
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000473 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000474 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000475
Daniel Jasper337816e2013-01-11 10:22:12 +0000476 bool operator<(const ParenState &Other) const {
477 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000478 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000479 if (LastSpace != Other.LastSpace)
480 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000481 if (AssignmentColumn != Other.AssignmentColumn)
482 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000483 if (FirstLessLess != Other.FirstLessLess)
484 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000485 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
486 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000487 if (QuestionColumn != Other.QuestionColumn)
488 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000489 if (BreakAfterComma != Other.BreakAfterComma)
490 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000491 if (HasMultiParameterLine != Other.HasMultiParameterLine)
492 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000493 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000494 }
495 };
496
497 /// \brief The current state when indenting a unwrapped line.
498 ///
499 /// As the indenting tries different combinations this is copied by value.
500 struct LineState {
501 /// \brief The number of used columns in the current line.
502 unsigned Column;
503
504 /// \brief The token that needs to be next formatted.
505 const AnnotatedToken *NextToken;
506
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000507 /// \brief The column of the first variable in a for-loop declaration.
508 ///
509 /// Used to align the second variable if necessary.
510 unsigned ForLoopVariablePos;
511
512 /// \brief \c true if this line contains a continued for-loop section.
513 bool LineContainsContinuedForLoopSection;
514
Daniel Jasper337816e2013-01-11 10:22:12 +0000515 /// \brief A stack keeping track of properties applying to parenthesis
516 /// levels.
517 std::vector<ParenState> Stack;
518
519 /// \brief Comparison operator to be able to used \c LineState in \c map.
520 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000521 if (Other.NextToken != NextToken)
522 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000523 if (Other.Column != Column)
524 return Other.Column > Column;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000525 if (Other.ForLoopVariablePos != ForLoopVariablePos)
526 return Other.ForLoopVariablePos < ForLoopVariablePos;
527 if (Other.LineContainsContinuedForLoopSection !=
528 LineContainsContinuedForLoopSection)
529 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000531 }
532 };
533
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000534 /// \brief Appends the next token to \p State and updates information
535 /// necessary for indentation.
536 ///
537 /// Puts the token on the current line if \p Newline is \c true and adds a
538 /// line break and necessary indentation otherwise.
539 ///
540 /// If \p DryRun is \c false, also creates and stores the required
541 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000543 const AnnotatedToken &Current = *State.NextToken;
544 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 assert(State.Stack.size());
546 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000547
548 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000549 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000550 if (Current.is(tok::r_brace)) {
551 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000552 } else if (Current.is(tok::string_literal) &&
553 Previous.is(tok::string_literal)) {
554 State.Column = State.Column - Previous.FormatTok.TokenLength;
555 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000556 State.Stack[ParenLevel].FirstLessLess != 0) {
557 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000558 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000559 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000560 Current.is(tok::period) || Current.is(tok::arrow) ||
561 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000562 // Indent and extra 4 spaces after if we know the current expression is
563 // continued. Don't do that on the top level, as we already indent 4
564 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000565 State.Column = std::max(State.Stack.back().LastSpace,
566 State.Stack.back().Indent) + 4;
567 } else if (Current.Type == TT_ConditionalExpr) {
568 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000569 } else if (RootToken.is(tok::kw_for) && ParenLevel == 1 &&
570 Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000571 State.Column = State.ForLoopVariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000572 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
573 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000574 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000575 } else if (Previous.Type == TT_BinaryOperator &&
576 State.Stack.back().AssignmentColumn != 0) {
577 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000578 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000579 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000580 }
581
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000582 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000583 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000584
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000585 if (!DryRun) {
586 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000587 Whitespaces.replaceWhitespace(Current, 1, State.Column,
588 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000589 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000590 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
591 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000592 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000593
Daniel Jasper337816e2013-01-11 10:22:12 +0000594 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000595 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000596 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000597 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000598 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
599 State.ForLoopVariablePos = State.Column -
600 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000601
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000602 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
603 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000604 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000605
Daniel Jasperf7935112012-12-03 18:12:45 +0000606 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000607 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000608
Daniel Jasperbcab4302013-01-09 10:40:23 +0000609 // FIXME: Do we need to do this for assignments nested in other
610 // expressions?
611 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000612 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000613 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000614 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000615 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000616 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000617 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000618 if (Current.getPreviousNoneComment() != NULL &&
619 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000620 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000621 State.Stack[ParenLevel].HasMultiParameterLine = true;
622
Daniel Jaspere9de2602012-12-06 09:56:08 +0000623 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000624 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
625 // Treat the condition inside an if as if it was a second function
626 // parameter, i.e. let nested calls have an indent of 4.
627 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000628 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000629 // Top-level spaces are exempt as that mostly leads to better results.
630 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000631 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000632 Previous.Type == TT_ConditionalExpr ||
633 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000634 getPrecedence(Previous) != prec::Assignment)
635 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000636 else if (Previous.ParameterCount > 1 &&
637 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
638 Previous.Type == TT_TemplateOpener))
639 // If this function has multiple parameters, indent nested calls from
640 // the start of the first parameter.
641 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000642 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000643
644 // If we break after an {, we should also break before the corresponding }.
645 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000646 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000647
Daniel Jaspere941b162013-01-23 10:08:28 +0000648 if (!Style.BinPackParameters && Newline) {
649 // If we are breaking after '(', '{', '<', this is not bin packing unless
650 // AllowAllParametersOnNextLine is false.
651 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
652 Previous.Type != TT_TemplateOpener) ||
653 !Style.AllowAllParametersOnNextLine)
654 State.Stack.back().BreakAfterComma = true;
655
656 // Any break on this level means that the parent level has been broken
657 // and we need to avoid bin packing there.
658 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
659 State.Stack[i].BreakAfterComma = true;
660 }
661 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000662
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000663 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000664 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000665
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000666 /// \brief Mark the next token as consumed in \p State and modify its stacks
667 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000668 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000669 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000670 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000671
Daniel Jasper337816e2013-01-11 10:22:12 +0000672 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
673 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000674 if (Current.is(tok::question))
675 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000676
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000677 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000678 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000679 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
680 Current.is(tok::l_brace) ||
681 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000682 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000683 if (Current.is(tok::l_brace)) {
684 // FIXME: This does not work with nested static initializers.
685 // Implement a better handling for static initializers and similar
686 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000687 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000688 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000689 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000690 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000691 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000692 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000693 }
694
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000695 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000696 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000697 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
698 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
699 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000700 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000701 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000702
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000703 if (State.NextToken->Children.empty())
704 State.NextToken = NULL;
705 else
706 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000707
708 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000709 }
710
Nico Weber49cbc2c2013-01-07 15:15:29 +0000711 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000712 unsigned splitPenalty(const AnnotatedToken &Tok) {
713 const AnnotatedToken &Left = Tok;
714 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000715
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000716 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
717 return 50;
718 if (Left.is(tok::equal) && Right.is(tok::l_brace))
719 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000720 if (Left.is(tok::coloncolon))
721 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000722
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000723 if (Left.Type == TT_RangeBasedForLoopColon)
724 return 5;
725
Daniel Jasper48c62f92013-01-28 17:30:17 +0000726 if (Right.is(tok::arrow) || Right.is(tok::period)) {
727 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
728 return 5; // Should be smaller than breaking at a nested comma.
729 return 150;
730 }
731
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000732 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000733 if (RootToken.is(tok::kw_for) &&
734 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000735 return 20;
736
Daniel Jasper04468962013-01-18 10:56:38 +0000737 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000739
740 // In Objective-C method expressions, prefer breaking before "param:" over
741 // breaking after it.
742 if (isObjCSelectorName(Right))
743 return 0;
744 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
745 return 20;
746
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000747 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000748 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000749 // FIXME: The penalty for a trailing "<" or "[" being higher than the
750 // penalty for a trainling "(" is a temporary workaround until we can
751 // properly avoid breaking in array subscripts or template parameters.
752 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
753 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000754
Daniel Jasperca6623b2013-01-28 12:45:14 +0000755 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper399d24b2013-01-09 07:06:56 +0000756 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000757 prec::Level Level = getPrecedence(Left);
758
Daniel Jasperde5c2072012-12-24 00:13:23 +0000759 if (Level != prec::Unknown)
760 return Level;
761
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 return 3;
763 }
764
Daniel Jasper2df93312013-01-09 10:16:05 +0000765 unsigned getColumnLimit() {
766 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
767 }
768
Daniel Jasperf7935112012-12-03 18:12:45 +0000769 /// \brief Calculate the number of lines needed to format the remaining part
770 /// of the unwrapped line.
771 ///
772 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000773 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 /// added after the previous token.
775 ///
776 /// \param StopAt is used for optimization. If we can determine that we'll
777 /// definitely need at least \p StopAt additional lines, we already know of a
778 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000779 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000780 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000781 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000782 return 0;
783
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000784 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000786 if (NewLine && !State.NextToken->CanBreakBefore &&
787 !(State.NextToken->is(tok::r_brace) &&
788 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000789 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000790 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000791 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000792 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000793 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000794 State.LineContainsContinuedForLoopSection)
795 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000796 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000797 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000798 State.Stack.back().BreakAfterComma)
799 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000800 // Trying to insert a parameter on a new line if there are already more than
801 // one parameter on the current line is bin packing.
802 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
803 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
804 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000805 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
806 (State.NextToken->Parent->ClosesTemplateDeclaration &&
807 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000808 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000809
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000810 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000811 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000812 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000813 splitPenalty(*State.NextToken->Parent);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000814
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000815 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000816
Daniel Jasper2df93312013-01-09 10:16:05 +0000817 // Exceeding column limit is bad, assign penalty.
818 if (State.Column > getColumnLimit()) {
819 unsigned ExcessCharacters = State.Column - getColumnLimit();
820 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
821 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000822
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 if (StopAt <= CurrentPenalty)
824 return UINT_MAX;
825 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000826 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000827 if (I != Memory.end()) {
828 // If this state has already been examined, we can safely return the
829 // previous result if we
830 // - have not hit the optimatization (and thus returned UINT_MAX) OR
831 // - are now computing for a smaller or equal StopAt.
832 unsigned SavedResult = I->second.first;
833 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000834 if (SavedResult != UINT_MAX)
835 return SavedResult + CurrentPenalty;
836 else if (StopAt <= SavedStopAt)
837 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000838 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000839
840 unsigned NoBreak = calcPenalty(State, false, StopAt);
841 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
842 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000843
844 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
845 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000846 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000847
848 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000849 }
850
Daniel Jasperf7935112012-12-03 18:12:45 +0000851 FormatStyle Style;
852 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000853 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000854 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000855 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000856 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000857
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000858 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000859 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000860 StateMap Memory;
861
Daniel Jasperf7935112012-12-03 18:12:45 +0000862 OptimizationParameters Parameters;
863};
864
865/// \brief Determines extra information about the tokens comprising an
866/// \c UnwrappedLine.
867class TokenAnnotator {
868public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000869 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
870 AnnotatedLine &Line)
871 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000872
873 /// \brief A parser that gathers additional information about tokens.
874 ///
875 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
876 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
877 /// into template parameter lists.
878 class AnnotatingParser {
879 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000880 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000881 : CurrentToken(&RootToken), KeywordVirtualFound(false),
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000882 ColonIsObjCMethodExpr(false), ColonIsForRangeExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000883
Nico Weber250fe712013-01-18 02:43:57 +0000884 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
885 struct ObjCSelectorRAII {
886 AnnotatingParser &P;
887 bool ColonWasObjCMethodExpr;
888
889 ObjCSelectorRAII(AnnotatingParser &P)
890 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
891
892 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
893
894 void markStart(AnnotatedToken &Left) {
895 P.ColonIsObjCMethodExpr = true;
896 Left.Type = TT_ObjCMethodExpr;
897 }
898
899 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
900 };
901
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000902 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000903 if (CurrentToken == NULL)
904 return false;
905 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000906 while (CurrentToken != NULL) {
907 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000908 Left->MatchingParen = CurrentToken;
909 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000910 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000911 next();
912 return true;
913 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000914 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
915 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000916 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000917 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
918 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000919 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000920 if (CurrentToken->is(tok::comma))
921 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000922 if (!consumeToken())
923 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000924 }
925 return false;
926 }
927
Nico Weber80a82762013-01-17 17:17:19 +0000928 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000929 if (CurrentToken == NULL)
930 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000931 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000932 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000933 if (CurrentToken->is(tok::caret)) {
934 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000935 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000936 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
937 // @selector( starts a selector.
938 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
939 MaybeSel->Parent->is(tok::at)) {
940 StartsObjCMethodExpr = true;
941 }
942 }
943
944 ObjCSelectorRAII objCSelector(*this);
945 if (StartsObjCMethodExpr)
946 objCSelector.markStart(*Left);
947
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000948 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000949 // LookForDecls is set when "if (" has been seen. Check for
950 // 'identifier' '*' 'identifier' followed by not '=' -- this
951 // '*' has to be a binary operator but determineStarAmpUsage() will
952 // categorize it as an unary operator, so set the right type here.
953 if (LookForDecls && !CurrentToken->Children.empty()) {
954 AnnotatedToken &Prev = *CurrentToken->Parent;
955 AnnotatedToken &Next = CurrentToken->Children[0];
956 if (Prev.Parent->is(tok::identifier) &&
957 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
958 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
959 Prev.Type = TT_BinaryOperator;
960 LookForDecls = false;
961 }
962 }
963
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000965 Left->MatchingParen = CurrentToken;
966 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000967
968 if (StartsObjCMethodExpr)
969 objCSelector.markEnd(*CurrentToken);
970
Daniel Jasperf7935112012-12-03 18:12:45 +0000971 next();
972 return true;
973 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000974 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000975 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000976 if (CurrentToken->is(tok::comma))
977 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000978 if (!consumeToken())
979 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000980 }
981 return false;
982 }
983
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000984 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000985 if (!CurrentToken)
986 return false;
987
988 // A '[' could be an index subscript (after an indentifier or after
989 // ')' or ']'), or it could be the start of an Objective-C method
990 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000991 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000992 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000993 !Left->Parent || Left->Parent->is(tok::colon) ||
994 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
995 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
996 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000997 true, true) > prec::Unknown;
998
Nico Weber250fe712013-01-18 02:43:57 +0000999 ObjCSelectorRAII objCSelector(*this);
1000 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +00001001 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +00001002
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001003 while (CurrentToken != NULL) {
1004 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +00001005 if (!CurrentToken->Children.empty() &&
1006 CurrentToken->Children[0].is(tok::l_paren)) {
1007 // An ObjC method call can't be followed by an open parenthesis.
1008 // FIXME: Do we incorrectly label ":" with this?
1009 StartsObjCMethodExpr = false;
1010 Left->Type = TT_Unknown;
1011 }
Nico Weber250fe712013-01-18 02:43:57 +00001012 if (StartsObjCMethodExpr)
1013 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001014 Left->MatchingParen = CurrentToken;
1015 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 next();
1017 return true;
1018 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001020 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001021 if (CurrentToken->is(tok::comma))
1022 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001023 if (!consumeToken())
1024 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001025 }
1026 return false;
1027 }
1028
Daniel Jasper83a54d22013-01-10 09:26:47 +00001029 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001030 // Lines are fine to end with '{'.
1031 if (CurrentToken == NULL)
1032 return true;
1033 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001034 while (CurrentToken != NULL) {
1035 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001036 Left->MatchingParen = CurrentToken;
1037 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001038 next();
1039 return true;
1040 }
1041 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1042 return false;
1043 if (!consumeToken())
1044 return false;
1045 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001046 return true;
1047 }
1048
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001049 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001050 while (CurrentToken != NULL) {
1051 if (CurrentToken->is(tok::colon)) {
1052 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001053 next();
1054 return true;
1055 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001056 if (!consumeToken())
1057 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 }
1059 return false;
1060 }
1061
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001062 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001063 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1064 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001065 next();
1066 if (!parseAngle())
1067 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001069 return true;
1070 }
1071 return false;
1072 }
1073
Daniel Jasperc0880a92013-01-04 18:52:56 +00001074 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001075 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001078 case tok::plus:
1079 case tok::minus:
1080 // At the start of the line, +/- specific ObjectiveC method
1081 // declarations.
1082 if (Tok->Parent == NULL)
1083 Tok->Type = TT_ObjCMethodSpecifier;
1084 break;
Nico Webera7252d82013-01-12 06:18:40 +00001085 case tok::colon:
1086 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001087 if (Tok->Parent->is(tok::r_paren))
1088 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001089 else if (ColonIsObjCMethodExpr)
Nico Webera7252d82013-01-12 06:18:40 +00001090 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001091 else if (ColonIsForRangeExpr)
1092 Tok->Type = TT_RangeBasedForLoopColon;
Nico Webera7252d82013-01-12 06:18:40 +00001093 break;
Nico Weber80a82762013-01-17 17:17:19 +00001094 case tok::kw_if:
1095 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001096 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001097 next();
1098 if (!parseParens(/*LookForDecls=*/true))
1099 return false;
1100 }
1101 break;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001102 case tok::kw_for:
1103 ColonIsForRangeExpr = true;
1104 next();
1105 if (!parseParens())
1106 return false;
1107 break;
Nico Webera5510af2013-01-18 05:50:57 +00001108 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001109 if (!parseParens())
1110 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001111 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001113 if (!parseSquare())
1114 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001115 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001116 case tok::l_brace:
1117 if (!parseBrace())
1118 return false;
1119 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001120 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001121 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001123 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 Tok->Type = TT_BinaryOperator;
1125 CurrentToken = Tok;
1126 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001127 }
1128 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001129 case tok::r_paren:
1130 case tok::r_square:
1131 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001132 case tok::r_brace:
1133 // Lines can start with '}'.
1134 if (Tok->Parent != NULL)
1135 return false;
1136 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001138 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001139 break;
1140 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001141 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001143 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001144 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1145 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001146 next();
1147 }
1148 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001149 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1150 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001151 next();
1152 }
1153 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001154 break;
1155 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001156 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001157 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001158 case tok::kw_template:
1159 parseTemplateDeclaration();
1160 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001161 default:
1162 break;
1163 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001164 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001165 }
1166
Daniel Jasper050948a52012-12-21 17:58:39 +00001167 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001168 next();
1169 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1170 next();
1171 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001172 if (CurrentToken->isNot(tok::comment) ||
1173 !CurrentToken->Children.empty())
1174 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001175 next();
1176 }
1177 } else {
1178 while (CurrentToken != NULL) {
1179 next();
1180 }
1181 }
1182 }
1183
1184 void parseWarningOrError() {
1185 next();
1186 // We still want to format the whitespace left of the first token of the
1187 // warning or error.
1188 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001189 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001190 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001191 next();
1192 }
1193 }
1194
1195 void parsePreprocessorDirective() {
1196 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001197 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001198 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001199 // Hashes in the middle of a line can lead to any strange token
1200 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001201 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001202 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001203 switch (
1204 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001205 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001206 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001207 parseIncludeDirective();
1208 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001209 case tok::pp_error:
1210 case tok::pp_warning:
1211 parseWarningOrError();
1212 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001213 default:
1214 break;
1215 }
1216 }
1217
Daniel Jasperda16db32013-01-07 10:48:50 +00001218 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001219 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001220 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001222 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001223 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001224 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001225 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001226
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001227 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001228 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001229 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1230 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001231 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1232 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1233 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001234 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001235 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001236 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001237 if (KeywordVirtualFound)
1238 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001239
1240 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001241 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001242 return LT_BuilderTypeCall;
1243
Daniel Jasperda16db32013-01-07 10:48:50 +00001244 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245 }
1246
1247 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001248 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1249 CurrentToken = &CurrentToken->Children[0];
1250 else
1251 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001252 }
1253
1254 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001255 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001256 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001257 bool ColonIsObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001258 bool ColonIsForRangeExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001259 };
1260
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001261 void calculateExtraInformation(AnnotatedToken &Current) {
1262 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1263
Manuel Klimek52b15152013-01-09 15:25:02 +00001264 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001265 Current.MustBreakBefore = true;
1266 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001267 if (Current.Type == TT_LineComment) {
1268 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001269 } else if ((Current.Parent->is(tok::comment) &&
1270 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001271 (Current.is(tok::string_literal) &&
1272 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001273 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001274 } else {
1275 Current.MustBreakBefore = false;
1276 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001277 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001278 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001279 if (Current.MustBreakBefore)
1280 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1281 else
1282 Current.TotalLength = Current.Parent->TotalLength +
1283 Current.FormatTok.TokenLength +
1284 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001285 if (!Current.Children.empty())
1286 calculateExtraInformation(Current.Children[0]);
1287 }
1288
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001289 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001290 AnnotatingParser Parser(Line.First);
1291 Line.Type = Parser.parseLine();
1292 if (Line.Type == LT_Invalid)
1293 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001294
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001295 bool LookForFunctionName = Line.MustBeDeclaration;
1296 determineTokenTypes(Line.First, /*IsExpression=*/ false,
1297 LookForFunctionName);
Daniel Jasperda16db32013-01-07 10:48:50 +00001298
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001299 if (Line.First.Type == TT_ObjCMethodSpecifier)
1300 Line.Type = LT_ObjCMethodDecl;
1301 else if (Line.First.Type == TT_ObjCDecl)
1302 Line.Type = LT_ObjCDecl;
1303 else if (Line.First.Type == TT_ObjCProperty)
1304 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001305
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001306 Line.First.SpaceRequiredBefore = true;
1307 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1308 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001309
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001310 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001311 if (!Line.First.Children.empty())
1312 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001313 }
1314
1315private:
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001316 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression,
1317 bool LookForFunctionName) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001318 if (getPrecedence(Current) == prec::Assignment) {
1319 IsExpression = true;
1320 AnnotatedToken *Previous = Current.Parent;
1321 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001322 if (Previous->Type == TT_BinaryOperator &&
1323 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001324 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001325 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001326 Previous = Previous->Parent;
1327 }
1328 }
1329 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001330 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1331 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001332 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001333
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001334 if (Current.Type == TT_Unknown) {
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001335 if (LookForFunctionName && Current.is(tok::l_paren)) {
1336 findFunctionName(&Current);
1337 LookForFunctionName = false;
1338 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001339 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001340 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1341 Current.is(tok::caret)) {
1342 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001343 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1344 Current.Type = determineIncrementUsage(Current);
1345 } else if (Current.is(tok::exclaim)) {
1346 Current.Type = TT_UnaryOperator;
1347 } else if (isBinaryOperator(Current)) {
1348 Current.Type = TT_BinaryOperator;
1349 } else if (Current.is(tok::comment)) {
1350 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1351 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001352 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001353 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001354 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001355 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001356 } else if (Current.is(tok::r_paren) &&
1357 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001358 Current.Parent->Type == TT_TemplateCloser) &&
1359 (Current.Children.empty() ||
1360 (Current.Children[0].isNot(tok::equal) &&
1361 Current.Children[0].isNot(tok::semi) &&
1362 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001363 // FIXME: We need to get smarter and understand more cases of casts.
1364 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001365 } else if (Current.is(tok::at) && Current.Children.size()) {
1366 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1367 case tok::objc_interface:
1368 case tok::objc_implementation:
1369 case tok::objc_protocol:
1370 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001371 break;
1372 case tok::objc_property:
1373 Current.Type = TT_ObjCProperty;
1374 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001375 default:
1376 break;
1377 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001378 }
1379 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001380
1381 if (!Current.Children.empty())
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001382 determineTokenTypes(Current.Children[0], IsExpression,
1383 LookForFunctionName);
1384 }
1385
1386 /// \brief Starting from \p Current, this searches backwards for an
1387 /// identifier which could be the start of a function name and marks it.
1388 void findFunctionName(AnnotatedToken *Current) {
1389 AnnotatedToken *Parent = Current->Parent;
1390 while (Parent != NULL && Parent->Parent != NULL) {
1391 if (Parent->is(tok::identifier) &&
1392 (Parent->Parent->is(tok::identifier) ||
1393 Parent->Parent->Type == TT_PointerOrReference ||
1394 Parent->Parent->Type == TT_TemplateCloser)) {
1395 Parent->Type = TT_StartOfName;
1396 break;
1397 }
1398 Parent = Parent->Parent;
1399 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001400 }
1401
Daniel Jasper71945272013-01-15 14:27:39 +00001402 /// \brief Returns the previous token ignoring comments.
1403 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1404 const AnnotatedToken *PrevToken = Tok.Parent;
1405 while (PrevToken != NULL && PrevToken->is(tok::comment))
1406 PrevToken = PrevToken->Parent;
1407 return PrevToken;
1408 }
1409
1410 /// \brief Returns the next token ignoring comments.
1411 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1412 if (Tok.Children.empty())
1413 return NULL;
1414 const AnnotatedToken *NextToken = &Tok.Children[0];
1415 while (NextToken->is(tok::comment)) {
1416 if (NextToken->Children.empty())
1417 return NULL;
1418 NextToken = &NextToken->Children[0];
1419 }
1420 return NextToken;
1421 }
1422
1423 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001424 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1425 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001426 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1427 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001428 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001429
1430 const AnnotatedToken *NextToken = getNextToken(Tok);
1431 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001432 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001433
Daniel Jasper0b820602013-01-22 11:46:26 +00001434 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1435 return TT_PointerOrReference;
1436
Daniel Jasper71945272013-01-15 14:27:39 +00001437 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1438 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1439 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1440 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001441 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001442 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001443
Daniel Jasper71945272013-01-15 14:27:39 +00001444 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1445 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1446 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1447 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1448 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1449 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1450 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001451 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001452
Daniel Jasper71945272013-01-15 14:27:39 +00001453 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1454 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001455 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001456
Daniel Jasper426702d2012-12-05 07:51:39 +00001457 // It is very unlikely that we are going to find a pointer or reference type
1458 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001459 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001460 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001461
Daniel Jasperda16db32013-01-07 10:48:50 +00001462 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001463 }
1464
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001465 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001466 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1467 if (PrevToken == NULL)
1468 return TT_UnaryOperator;
1469
Daniel Jasper8dd40472012-12-21 09:41:31 +00001470 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001471 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1472 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1473 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1474 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1475 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001476 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001477
1478 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001479 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001480 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001481
1482 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001483 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001484 }
1485
1486 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001487 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001488 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1489 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001490 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001491 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1492 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001493 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001494
Daniel Jasperda16db32013-01-07 10:48:50 +00001495 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001496 }
1497
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001498 bool spaceRequiredBetween(const AnnotatedToken &Left,
1499 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001500 if (Right.is(tok::hashhash))
1501 return Left.is(tok::hash);
1502 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1503 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001504 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1505 return false;
Nico Webera6087752013-01-10 20:12:55 +00001506 if (Right.is(tok::less) &&
1507 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001508 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001509 return true;
1510 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1511 return false;
1512 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1513 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001514 if (Left.is(tok::at) &&
1515 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1516 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001517 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1518 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001519 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001520 if (Left.is(tok::coloncolon))
1521 return false;
1522 if (Right.is(tok::coloncolon))
1523 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001524 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1525 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001526 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001527 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001528 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1529 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001530 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001531 return Right.FormatTok.Tok.isLiteral() ||
1532 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 if (Right.is(tok::star) && Left.is(tok::l_paren))
1534 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001535 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1536 return false;
1537 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001538 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001539 if (Left.is(tok::period) || Right.is(tok::period))
1540 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001541 if (Left.is(tok::colon))
1542 return Left.Type != TT_ObjCMethodExpr;
1543 if (Right.is(tok::colon))
1544 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001545 if (Left.is(tok::l_paren))
1546 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001547 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001548 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001549 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001550 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001551 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1552 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001553 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001554 if (Left.is(tok::at) &&
1555 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001556 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001557 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1558 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001559 return true;
1560 }
1561
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001562 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001563 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001564 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1565 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001566 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001567 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001568 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001569 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001570 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001571 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001572 // Don't space between ')' and <id>
1573 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001575 // Don't space between ':' and '('
1576 return false;
1577 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001578 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001579 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1580 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001581
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001582 if (Tok.Parent->is(tok::comma))
1583 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001584 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001585 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001586 if (Tok.Type == TT_OverloadedOperator)
1587 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001588 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001589 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001590 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001591 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001592 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001593 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001594 if (Tok.Parent->Type == TT_UnaryOperator ||
1595 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001596 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001597 if (Tok.Type == TT_UnaryOperator)
1598 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001599 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1600 (Tok.Parent->isNot(tok::colon) ||
1601 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001602 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1603 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001604 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1605 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001606 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001607 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001608 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001609 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001610 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001611 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001612 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001613 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001614 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001615 }
1616
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001617 bool canBreakBefore(const AnnotatedToken &Right) {
1618 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001619 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001620 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1621 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001622 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001623 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1624 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001625 // Don't break this identifier as ':' or identifier
1626 // before it will break.
1627 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001628 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1629 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001630 // Don't break at ':' if identifier before it can beak.
1631 return false;
1632 }
Daniel Jasperd36ef5e2013-01-28 15:40:20 +00001633 if (Right.Type == TT_StartOfName && Style.AllowReturnTypeOnItsOwnLine)
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001634 return true;
Nico Webera7252d82013-01-12 06:18:40 +00001635 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1636 return false;
1637 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1638 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001639 if (isObjCSelectorName(Right))
1640 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001641 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001642 return true;
Daniel Jasperca6623b2013-01-28 12:45:14 +00001643 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1644 return true;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001645 if (Left.Type == TT_RangeBasedForLoopColon)
1646 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001647 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperca6623b2013-01-28 12:45:14 +00001648 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1649 Left.is(tok::question))
Daniel Jasperd1926a32013-01-02 08:44:14 +00001650 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001651 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001652 return false;
1653
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001654 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001655 // We rely on MustBreakBefore being set correctly here as we should not
1656 // change the "binding" behavior of a comment.
1657 return false;
1658
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001659 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1660 // unless it is follow by ';', '{' or '='.
1661 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1662 Left.Parent->is(tok::r_paren))
1663 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1664 Right.isNot(tok::equal);
1665
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001666 // We only break before r_brace if there was a corresponding break before
1667 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1668 if (Right.is(tok::r_brace))
1669 return false;
1670
Daniel Jasper71945272013-01-15 14:27:39 +00001671 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001672 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001673 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1674 Left.is(tok::comma) || Right.is(tok::lessless) ||
1675 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001676 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1677 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001678 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1679 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001680 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1681 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001682 }
1683
Daniel Jasperf7935112012-12-03 18:12:45 +00001684 FormatStyle Style;
1685 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001686 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001687 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001688};
1689
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001690class LexerBasedFormatTokenSource : public FormatTokenSource {
1691public:
1692 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001693 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001694 IdentTable(Lex.getLangOpts()) {
1695 Lex.SetKeepWhitespaceMode(true);
1696 }
1697
1698 virtual FormatToken getNextToken() {
1699 if (GreaterStashed) {
1700 FormatTok.NewlinesBefore = 0;
1701 FormatTok.WhiteSpaceStart =
1702 FormatTok.Tok.getLocation().getLocWithOffset(1);
1703 FormatTok.WhiteSpaceLength = 0;
1704 GreaterStashed = false;
1705 return FormatTok;
1706 }
1707
1708 FormatTok = FormatToken();
1709 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001710 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001711 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001712 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1713 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001714
1715 // Consume and record whitespace until we find a significant token.
1716 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001717 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001718 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1719 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001720 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1721
1722 if (FormatTok.Tok.is(tok::eof))
1723 return FormatTok;
1724 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001725 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001726 }
Manuel Klimekef920692013-01-07 07:56:50 +00001727
1728 // Now FormatTok is the next non-whitespace token.
1729 FormatTok.TokenLength = Text.size();
1730
Manuel Klimek1abf7892013-01-04 23:34:14 +00001731 // In case the token starts with escaped newlines, we want to
1732 // take them into account as whitespace - this pattern is quite frequent
1733 // in macro definitions.
1734 // FIXME: What do we want to do with other escaped spaces, and escaped
1735 // spaces or newlines in the middle of tokens?
1736 // FIXME: Add a more explicit test.
1737 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001738 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001739 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001740 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001741 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001742 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001743 }
1744
1745 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001746 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001747 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001748 FormatTok.Tok.setKind(Info.getTokenID());
1749 }
1750
1751 if (FormatTok.Tok.is(tok::greatergreater)) {
1752 FormatTok.Tok.setKind(tok::greater);
1753 GreaterStashed = true;
1754 }
1755
1756 return FormatTok;
1757 }
1758
1759private:
1760 FormatToken FormatTok;
1761 bool GreaterStashed;
1762 Lexer &Lex;
1763 SourceManager &SourceMgr;
1764 IdentifierTable IdentTable;
1765
1766 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001767 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001768 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1769 Tok.getLength());
1770 }
1771};
1772
Daniel Jasperf7935112012-12-03 18:12:45 +00001773class Formatter : public UnwrappedLineConsumer {
1774public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001775 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1776 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001777 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001778 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001779 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001780
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001781 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001782
Daniel Jasperf7935112012-12-03 18:12:45 +00001783 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001784 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001785 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001786 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001787 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001788 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1789 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1790 Annotator.annotate();
1791 }
1792 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1793 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001794 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001795 const AnnotatedLine &TheLine = *I;
1796 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1797 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1798 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001799 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001800 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001801 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001802 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001803 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001804 PreviousEndOfLineColumn = Formatter.format();
1805 } else {
1806 // If we did not reformat this unwrapped line, the column at the end of
1807 // the last token is unchanged - thus, we can calculate the end of the
1808 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001809 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001810 SourceMgr.getSpellingColumnNumber(
1811 TheLine.Last->FormatTok.Tok.getLocation()) +
1812 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1813 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001814 1;
1815 }
1816 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001817 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001818 }
1819
1820private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001821 /// \brief Tries to merge lines into one.
1822 ///
1823 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1824 /// if possible; note that \c I will be incremented when lines are merged.
1825 ///
1826 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001827 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001828 std::vector<AnnotatedLine>::iterator &I,
1829 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001830 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1831
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001832 // We can never merge stuff if there are trailing line comments.
1833 if (I->Last->Type == TT_LineComment)
1834 return;
1835
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001836 // Check whether the UnwrappedLine can be put onto a single line. If
1837 // so, this is bound to be the optimal solution (by definition) and we
1838 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001839 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001840 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001841 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001842
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001843 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001844 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001845
Daniel Jasper25837aa2013-01-14 14:14:23 +00001846 if (I->Last->is(tok::l_brace)) {
1847 tryMergeSimpleBlock(I, E, Limit);
1848 } else if (I->First.is(tok::kw_if)) {
1849 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001850 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1851 I->First.FormatTok.IsFirst)) {
1852 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001853 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001854 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001855 }
1856
Daniel Jasper39825ea2013-01-14 15:40:57 +00001857 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1858 std::vector<AnnotatedLine>::iterator E,
1859 unsigned Limit) {
1860 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001861 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1862 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001863 if (I + 2 != E && (I + 2)->InPPDirective &&
1864 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1865 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001866 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001867 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001868 join(Line, *(++I));
1869 }
1870
Daniel Jasper25837aa2013-01-14 14:14:23 +00001871 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1872 std::vector<AnnotatedLine>::iterator E,
1873 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001874 if (!Style.AllowShortIfStatementsOnASingleLine)
1875 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001876 if ((I + 1)->InPPDirective != I->InPPDirective ||
1877 ((I + 1)->InPPDirective &&
1878 (I + 1)->First.FormatTok.HasUnescapedNewline))
1879 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001880 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001881 if (Line.Last->isNot(tok::r_paren))
1882 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001883 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001884 return;
1885 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1886 return;
1887 // Only inline simple if's (no nested if or else).
1888 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1889 return;
1890 join(Line, *(++I));
1891 }
1892
1893 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1894 std::vector<AnnotatedLine>::iterator E,
1895 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001896 // First, check that the current line allows merging. This is the case if
1897 // we're not in a control flow statement and the last token is an opening
1898 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001899 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001900 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001901 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1902 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1903 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1904 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001905 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001906 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1907 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001908 if (!AllowedTokens)
1909 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001910
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001911 AnnotatedToken *Tok = &(I + 1)->First;
1912 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1913 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1914 Tok->SpaceRequiredBefore = false;
1915 join(Line, *(I + 1));
1916 I += 1;
1917 } else {
1918 // Check that we still have three lines and they fit into the limit.
1919 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1920 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001921 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001922
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001923 // Second, check that the next line does not contain any braces - if it
1924 // does, readability declines when putting it into a single line.
1925 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1926 return;
1927 do {
1928 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1929 return;
1930 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1931 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001932
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001933 // Last, check that the third line contains a single closing brace.
1934 Tok = &(I + 2)->First;
1935 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1936 Tok->MustBreakBefore)
1937 return;
1938
1939 join(Line, *(I + 1));
1940 join(Line, *(I + 2));
1941 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001942 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001943 }
1944
1945 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1946 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001947 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1948 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001949 }
1950
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001951 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1952 A.Last->Children.push_back(B.First);
1953 while (!A.Last->Children.empty()) {
1954 A.Last->Children[0].Parent = A.Last;
1955 A.Last = &A.Last->Children[0];
1956 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001957 }
1958
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001959 bool touchesRanges(const AnnotatedLine &TheLine) {
1960 const FormatToken *First = &TheLine.First.FormatTok;
1961 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001962 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001963 First->Tok.getLocation(),
1964 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001965 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001966 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1967 Ranges[i].getBegin()) &&
1968 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1969 LineRange.getBegin()))
1970 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001971 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001972 return false;
1973 }
1974
1975 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001976 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001977 }
1978
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001979 /// \brief Add a new line and the required indent before the first Token
1980 /// of the \c UnwrappedLine if there was no structural parsing error.
1981 /// Returns the indent level of the \c UnwrappedLine.
1982 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1983 bool InPPDirective,
1984 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001985 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001986 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1987 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1988
1989 unsigned Newlines = std::min(Tok.NewlinesBefore,
1990 Style.MaxEmptyLinesToKeep + 1);
1991 if (Newlines == 0 && !Tok.IsFirst)
1992 Newlines = 1;
1993 unsigned Indent = Level * 2;
1994
1995 bool IsAccessModifier = false;
1996 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1997 RootToken.is(tok::kw_private))
1998 IsAccessModifier = true;
1999 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
2000 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
2001 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
2002 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
2003 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
2004 IsAccessModifier = true;
2005
2006 if (IsAccessModifier &&
2007 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
2008 Indent += Style.AccessModifierOffset;
2009 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002010 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002011 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002012 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
2013 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002014 }
2015 return Indent;
2016 }
2017
Alexander Kornienko116ba682013-01-14 11:34:14 +00002018 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00002019 FormatStyle Style;
2020 Lexer &Lex;
2021 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002022 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00002023 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00002024 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00002025 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00002026};
2027
2028tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2029 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002030 std::vector<CharSourceRange> Ranges,
2031 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002032 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00002033 OwningPtr<DiagnosticConsumer> DiagPrinter;
2034 if (DiagClient == 0) {
2035 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
2036 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
2037 DiagClient = DiagPrinter.get();
2038 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002039 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002040 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002041 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002042 Diagnostics.setSourceManager(&SourceMgr);
2043 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002044 return formatter.format();
2045}
2046
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002047LangOptions getFormattingLangOpts() {
2048 LangOptions LangOpts;
2049 LangOpts.CPlusPlus = 1;
2050 LangOpts.CPlusPlus11 = 1;
2051 LangOpts.Bool = 1;
2052 LangOpts.ObjC1 = 1;
2053 LangOpts.ObjC2 = 1;
2054 return LangOpts;
2055}
2056
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002057} // namespace format
2058} // namespace clang