blob: 80298df84457efd78aca0494a7a82d08f6cda552 [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;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000243 Comments.back().MaxColumn =
244 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000245 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) {
Daniel Jasperbbc84152013-01-29 11:27:30 +0000266 unsigned Offset =
267 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000268 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 Jasper38c11ce2013-01-29 11:21:01 +0000369 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000370 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;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000387 State.NextToken = State.NextToken->Children.empty()
388 ? NULL : &State.NextToken->Children[0];
Daniel Jasper997b08c2013-01-18 09:19:33 +0000389 } 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;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000422 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
423 Tok.getLength());
Manuel Klimek24998102013-01-16 14:55:28 +0000424 llvm::errs();
425 }
426
427 void DebugPenalty(unsigned Penalty, bool Winner) {
428 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
429 if (Penalty == UINT_MAX)
430 llvm::errs() << "MAX";
431 else
432 llvm::errs() << Penalty;
433 llvm::errs().resetColor();
434 }
435
Daniel Jasper337816e2013-01-11 10:22:12 +0000436 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000437 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000438 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000439 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000440 BreakAfterComma(false), HasMultiParameterLine(false) {
441 }
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 Jasperbbc84152013-01-29 11:27:30 +0000507 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000508 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000509 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000510 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000511
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 Jasper38c11ce2013-01-29 11:21:01 +0000525 if (Other.VariablePos != VariablePos)
526 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000527 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 Jasper38c11ce2013-01-29 11:21:01 +0000569 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
570 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
571 ParenLevel == 0)) {
572 State.Column = State.VariablePos;
Daniel Jasperd2639ef2013-01-28 15:16:31 +0000573 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
574 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000575 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000576 } else if (Previous.Type == TT_BinaryOperator &&
577 State.Stack.back().AssignmentColumn != 0) {
578 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000579 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000580 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000581 }
582
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000583 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000584 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000585
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000586 if (!DryRun) {
587 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000588 Whitespaces.replaceWhitespace(Current, 1, State.Column,
589 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000590 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000591 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
592 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000593 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000594
Daniel Jasper337816e2013-01-11 10:22:12 +0000595 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000596 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000597 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000598 } else {
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000599 if (Current.is(tok::equal) &&
600 (RootToken.is(tok::kw_for) || ParenLevel == 0))
601 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000602
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000603 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
604 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000605 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000606
Daniel Jasperf7935112012-12-03 18:12:45 +0000607 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000608 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000609
Daniel Jasperbcab4302013-01-09 10:40:23 +0000610 // FIXME: Do we need to do this for assignments nested in other
611 // expressions?
612 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000613 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000614 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000615 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000616 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000617 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000618 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000619 if (Current.getPreviousNoneComment() != NULL &&
620 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000621 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000622 State.Stack[ParenLevel].HasMultiParameterLine = true;
623
Daniel Jaspere9de2602012-12-06 09:56:08 +0000624 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000625 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
626 // Treat the condition inside an if as if it was a second function
627 // parameter, i.e. let nested calls have an indent of 4.
628 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000629 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000630 // Top-level spaces are exempt as that mostly leads to better results.
631 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000632 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000633 Previous.Type == TT_ConditionalExpr ||
634 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000635 getPrecedence(Previous) != prec::Assignment)
636 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000637 else if (Previous.ParameterCount > 1 &&
638 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
639 Previous.Type == TT_TemplateOpener))
640 // If this function has multiple parameters, indent nested calls from
641 // the start of the first parameter.
642 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000643 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000644
645 // If we break after an {, we should also break before the corresponding }.
646 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000647 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000648
Daniel Jaspere941b162013-01-23 10:08:28 +0000649 if (!Style.BinPackParameters && Newline) {
650 // If we are breaking after '(', '{', '<', this is not bin packing unless
651 // AllowAllParametersOnNextLine is false.
652 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
653 Previous.Type != TT_TemplateOpener) ||
654 !Style.AllowAllParametersOnNextLine)
655 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000656
Daniel Jaspere941b162013-01-23 10:08:28 +0000657 // Any break on this level means that the parent level has been broken
658 // and we need to avoid bin packing there.
659 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
660 State.Stack[i].BreakAfterComma = true;
661 }
662 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000663
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000664 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000665 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000666
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000667 /// \brief Mark the next token as consumed in \p State and modify its stacks
668 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000669 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000671 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000672
Daniel Jasper337816e2013-01-11 10:22:12 +0000673 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
674 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000675 if (Current.is(tok::question))
676 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000677
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000678 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000679 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
681 Current.is(tok::l_brace) ||
682 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000683 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000684 if (Current.is(tok::l_brace)) {
685 // FIXME: This does not work with nested static initializers.
686 // Implement a better handling for static initializers and similar
687 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000688 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000689 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000690 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000691 }
Daniel Jasperbbc84152013-01-29 11:27:30 +0000692 State.Stack.push_back(ParenState(NewIndent,
693 State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000694 }
695
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000696 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000697 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000698 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
699 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
700 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000701 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000702 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000703
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000704 if (State.NextToken->Children.empty())
705 State.NextToken = NULL;
706 else
707 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000708
709 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000710 }
711
Nico Weber49cbc2c2013-01-07 15:15:29 +0000712 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000713 unsigned splitPenalty(const AnnotatedToken &Tok) {
714 const AnnotatedToken &Left = Tok;
715 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000716
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000717 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
718 return 50;
719 if (Left.is(tok::equal) && Right.is(tok::l_brace))
720 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000721 if (Left.is(tok::coloncolon))
722 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000723
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000724 if (Left.Type == TT_RangeBasedForLoopColon)
725 return 5;
726
Daniel Jasper48c62f92013-01-28 17:30:17 +0000727 if (Right.is(tok::arrow) || Right.is(tok::period)) {
728 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
729 return 5; // Should be smaller than breaking at a nested comma.
730 return 150;
731 }
732
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000733 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000734 if (RootToken.is(tok::kw_for) &&
735 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000736 return 20;
737
Daniel Jasper04468962013-01-18 10:56:38 +0000738 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000739 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000740
741 // In Objective-C method expressions, prefer breaking before "param:" over
742 // breaking after it.
743 if (isObjCSelectorName(Right))
744 return 0;
745 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
746 return 20;
747
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000748 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000749 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000750 // FIXME: The penalty for a trailing "<" or "[" being higher than the
751 // penalty for a trainling "(" is a temporary workaround until we can
752 // properly avoid breaking in array subscripts or template parameters.
753 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
754 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000755
Daniel Jasperca6623b2013-01-28 12:45:14 +0000756 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper399d24b2013-01-09 07:06:56 +0000757 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000758 prec::Level Level = getPrecedence(Left);
759
Daniel Jasperde5c2072012-12-24 00:13:23 +0000760 if (Level != prec::Unknown)
761 return Level;
762
Daniel Jasperf7935112012-12-03 18:12:45 +0000763 return 3;
764 }
765
Daniel Jasper2df93312013-01-09 10:16:05 +0000766 unsigned getColumnLimit() {
767 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
768 }
769
Daniel Jasperf7935112012-12-03 18:12:45 +0000770 /// \brief Calculate the number of lines needed to format the remaining part
771 /// of the unwrapped line.
772 ///
773 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000774 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 /// added after the previous token.
776 ///
777 /// \param StopAt is used for optimization. If we can determine that we'll
778 /// definitely need at least \p StopAt additional lines, we already know of a
779 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000780 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000782 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000783 return 0;
784
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000785 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000786 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000787 if (NewLine && !State.NextToken->CanBreakBefore &&
788 !(State.NextToken->is(tok::r_brace) &&
789 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000790 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000791 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000792 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000793 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000794 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000795 State.LineContainsContinuedForLoopSection)
796 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000797 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000798 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000799 State.Stack.back().BreakAfterComma)
800 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000801 // Trying to insert a parameter on a new line if there are already more than
802 // one parameter on the current line is bin packing.
803 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
804 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
805 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000806 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
807 (State.NextToken->Parent->ClosesTemplateDeclaration &&
808 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000809 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000810
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000811 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000812 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000813 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000814 splitPenalty(*State.NextToken->Parent);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000815
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000816 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000817
Daniel Jasper2df93312013-01-09 10:16:05 +0000818 // Exceeding column limit is bad, assign penalty.
819 if (State.Column > getColumnLimit()) {
820 unsigned ExcessCharacters = State.Column - getColumnLimit();
821 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
822 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000823
Daniel Jasperf7935112012-12-03 18:12:45 +0000824 if (StopAt <= CurrentPenalty)
825 return UINT_MAX;
826 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000827 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000828 if (I != Memory.end()) {
829 // If this state has already been examined, we can safely return the
830 // previous result if we
831 // - have not hit the optimatization (and thus returned UINT_MAX) OR
832 // - are now computing for a smaller or equal StopAt.
833 unsigned SavedResult = I->second.first;
834 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000835 if (SavedResult != UINT_MAX)
836 return SavedResult + CurrentPenalty;
837 else if (StopAt <= SavedStopAt)
838 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000839 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000840
841 unsigned NoBreak = calcPenalty(State, false, StopAt);
842 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
843 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000844
845 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
846 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000847 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000848
849 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000850 }
851
Daniel Jasperf7935112012-12-03 18:12:45 +0000852 FormatStyle Style;
853 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000854 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000855 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000856 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000857 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000858
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000859 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000860 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000861 StateMap Memory;
862
Daniel Jasperf7935112012-12-03 18:12:45 +0000863 OptimizationParameters Parameters;
864};
865
866/// \brief Determines extra information about the tokens comprising an
867/// \c UnwrappedLine.
868class TokenAnnotator {
869public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000870 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
871 AnnotatedLine &Line)
Daniel Jasperbbc84152013-01-29 11:27:30 +0000872 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {
873 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000874
875 /// \brief A parser that gathers additional information about tokens.
876 ///
877 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
878 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
879 /// into template parameter lists.
880 class AnnotatingParser {
881 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000882 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000883 : CurrentToken(&RootToken), KeywordVirtualFound(false),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000884 ColonIsObjCMethodExpr(false), ColonIsForRangeExpr(false) {
885 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000886
Nico Weber250fe712013-01-18 02:43:57 +0000887 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
888 struct ObjCSelectorRAII {
889 AnnotatingParser &P;
890 bool ColonWasObjCMethodExpr;
891
892 ObjCSelectorRAII(AnnotatingParser &P)
Daniel Jasperbbc84152013-01-29 11:27:30 +0000893 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {
894 }
Nico Weber250fe712013-01-18 02:43:57 +0000895
896 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
897
898 void markStart(AnnotatedToken &Left) {
899 P.ColonIsObjCMethodExpr = true;
900 Left.Type = TT_ObjCMethodExpr;
901 }
902
903 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
904 };
905
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000906 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000907 if (CurrentToken == NULL)
908 return false;
909 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000910 while (CurrentToken != NULL) {
911 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000912 Left->MatchingParen = CurrentToken;
913 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000914 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 next();
916 return true;
917 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
919 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000920 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000921 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
922 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000923 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000924 if (CurrentToken->is(tok::comma))
925 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000926 if (!consumeToken())
927 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000928 }
929 return false;
930 }
931
Nico Weber80a82762013-01-17 17:17:19 +0000932 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000933 if (CurrentToken == NULL)
934 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000935 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000936 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000937 if (CurrentToken->is(tok::caret)) {
938 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000939 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000940 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
941 // @selector( starts a selector.
942 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
943 MaybeSel->Parent->is(tok::at)) {
944 StartsObjCMethodExpr = true;
945 }
946 }
947
948 ObjCSelectorRAII objCSelector(*this);
949 if (StartsObjCMethodExpr)
950 objCSelector.markStart(*Left);
951
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000952 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000953 // LookForDecls is set when "if (" has been seen. Check for
954 // 'identifier' '*' 'identifier' followed by not '=' -- this
955 // '*' has to be a binary operator but determineStarAmpUsage() will
956 // categorize it as an unary operator, so set the right type here.
957 if (LookForDecls && !CurrentToken->Children.empty()) {
958 AnnotatedToken &Prev = *CurrentToken->Parent;
959 AnnotatedToken &Next = CurrentToken->Children[0];
960 if (Prev.Parent->is(tok::identifier) &&
961 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
962 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
963 Prev.Type = TT_BinaryOperator;
964 LookForDecls = false;
965 }
966 }
967
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000968 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000969 Left->MatchingParen = CurrentToken;
970 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000971
972 if (StartsObjCMethodExpr)
973 objCSelector.markEnd(*CurrentToken);
974
Daniel Jasperf7935112012-12-03 18:12:45 +0000975 next();
976 return true;
977 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000978 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000979 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000980 if (CurrentToken->is(tok::comma))
981 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000982 if (!consumeToken())
983 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 }
985 return false;
986 }
987
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000988 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000989 if (!CurrentToken)
990 return false;
991
992 // A '[' could be an index subscript (after an indentifier or after
993 // ')' or ']'), or it could be the start of an Objective-C method
994 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000995 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000996 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000997 !Left->Parent || Left->Parent->is(tok::colon) ||
998 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
999 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
Daniel Jasperbbc84152013-01-29 11:27:30 +00001000 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(), true,
1001 true) > prec::Unknown;
Nico Webera7252d82013-01-12 06:18:40 +00001002
Nico Weber250fe712013-01-18 02:43:57 +00001003 ObjCSelectorRAII objCSelector(*this);
1004 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +00001005 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +00001006
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001007 while (CurrentToken != NULL) {
1008 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +00001009 if (!CurrentToken->Children.empty() &&
1010 CurrentToken->Children[0].is(tok::l_paren)) {
1011 // An ObjC method call can't be followed by an open parenthesis.
1012 // FIXME: Do we incorrectly label ":" with this?
1013 StartsObjCMethodExpr = false;
1014 Left->Type = TT_Unknown;
Daniel Jasper38c11ce2013-01-29 11:21:01 +00001015 }
Nico Weber250fe712013-01-18 02:43:57 +00001016 if (StartsObjCMethodExpr)
1017 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001018 Left->MatchingParen = CurrentToken;
1019 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001020 next();
1021 return true;
1022 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001023 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001024 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001025 if (CurrentToken->is(tok::comma))
1026 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001027 if (!consumeToken())
1028 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001029 }
1030 return false;
1031 }
1032
Daniel Jasper83a54d22013-01-10 09:26:47 +00001033 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001034 // Lines are fine to end with '{'.
1035 if (CurrentToken == NULL)
1036 return true;
1037 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001038 while (CurrentToken != NULL) {
1039 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001040 Left->MatchingParen = CurrentToken;
1041 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001042 next();
1043 return true;
1044 }
1045 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1046 return false;
1047 if (!consumeToken())
1048 return false;
1049 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001050 return true;
1051 }
1052
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001053 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 while (CurrentToken != NULL) {
1055 if (CurrentToken->is(tok::colon)) {
1056 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001057 next();
1058 return true;
1059 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001060 if (!consumeToken())
1061 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 }
1063 return false;
1064 }
1065
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001066 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001067 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1068 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001069 next();
1070 if (!parseAngle())
1071 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001072 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001073 return true;
1074 }
1075 return false;
1076 }
1077
Daniel Jasperc0880a92013-01-04 18:52:56 +00001078 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001079 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001080 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001081 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001082 case tok::plus:
1083 case tok::minus:
1084 // At the start of the line, +/- specific ObjectiveC method
1085 // declarations.
1086 if (Tok->Parent == NULL)
1087 Tok->Type = TT_ObjCMethodSpecifier;
1088 break;
Nico Webera7252d82013-01-12 06:18:40 +00001089 case tok::colon:
1090 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001091 if (Tok->Parent->is(tok::r_paren))
1092 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001093 else if (ColonIsObjCMethodExpr)
Nico Webera7252d82013-01-12 06:18:40 +00001094 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001095 else if (ColonIsForRangeExpr)
1096 Tok->Type = TT_RangeBasedForLoopColon;
Nico Webera7252d82013-01-12 06:18:40 +00001097 break;
Nico Weber80a82762013-01-17 17:17:19 +00001098 case tok::kw_if:
1099 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001100 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001101 next();
Daniel Jasperbbc84152013-01-29 11:27:30 +00001102 if (!parseParens(/*LookForDecls=*/ true))
Nico Weber80a82762013-01-17 17:17:19 +00001103 return false;
1104 }
1105 break;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001106 case tok::kw_for:
1107 ColonIsForRangeExpr = true;
1108 next();
1109 if (!parseParens())
1110 return false;
1111 break;
Nico Webera5510af2013-01-18 05:50:57 +00001112 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001113 if (!parseParens())
1114 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001115 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001116 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001117 if (!parseSquare())
1118 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001119 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001120 case tok::l_brace:
1121 if (!parseBrace())
1122 return false;
1123 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001124 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001125 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001127 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001128 Tok->Type = TT_BinaryOperator;
1129 CurrentToken = Tok;
1130 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001131 }
1132 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001133 case tok::r_paren:
1134 case tok::r_square:
1135 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001136 case tok::r_brace:
1137 // Lines can start with '}'.
1138 if (Tok->Parent != NULL)
1139 return false;
1140 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001141 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001143 break;
1144 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001145 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001146 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001147 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001148 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1149 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001150 next();
1151 }
1152 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001153 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1154 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001155 next();
1156 }
1157 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001158 break;
1159 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001160 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001161 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001162 case tok::kw_template:
1163 parseTemplateDeclaration();
1164 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001165 default:
1166 break;
1167 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001168 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001169 }
1170
Daniel Jasper050948a52012-12-21 17:58:39 +00001171 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001172 next();
1173 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1174 next();
1175 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001176 if (CurrentToken->isNot(tok::comment) ||
1177 !CurrentToken->Children.empty())
1178 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001179 next();
1180 }
1181 } else {
1182 while (CurrentToken != NULL) {
1183 next();
1184 }
1185 }
1186 }
1187
1188 void parseWarningOrError() {
1189 next();
1190 // We still want to format the whitespace left of the first token of the
1191 // warning or error.
1192 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001193 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001194 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001195 next();
1196 }
1197 }
1198
1199 void parsePreprocessorDirective() {
1200 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001201 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001202 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001203 // Hashes in the middle of a line can lead to any strange token
1204 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001205 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001206 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001207 switch (
1208 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001209 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001210 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001211 parseIncludeDirective();
1212 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001213 case tok::pp_error:
1214 case tok::pp_warning:
1215 parseWarningOrError();
1216 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001217 default:
1218 break;
1219 }
1220 }
1221
Daniel Jasperda16db32013-01-07 10:48:50 +00001222 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001223 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001224 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001225 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001226 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001227 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001228 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001229 while (CurrentToken != NULL) {
1230 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001231 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001232 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1233 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001234 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1235 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1236 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001237 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001238 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001239 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001240 if (KeywordVirtualFound)
1241 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001242
1243 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001244 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001245 return LT_BuilderTypeCall;
1246
Daniel Jasperda16db32013-01-07 10:48:50 +00001247 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001248 }
1249
1250 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001251 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1252 CurrentToken = &CurrentToken->Children[0];
1253 else
1254 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001255 }
1256
1257 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001258 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001259 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001260 bool ColonIsObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001261 bool ColonIsForRangeExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001262 };
1263
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001264 void calculateExtraInformation(AnnotatedToken &Current) {
1265 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1266
Manuel Klimek52b15152013-01-09 15:25:02 +00001267 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001268 Current.MustBreakBefore = true;
1269 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001270 if (Current.Type == TT_LineComment) {
1271 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001272 } else if ((Current.Parent->is(tok::comment) &&
1273 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001274 (Current.is(tok::string_literal) &&
1275 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001276 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001277 } else {
1278 Current.MustBreakBefore = false;
1279 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001280 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001281 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001282 if (Current.MustBreakBefore)
1283 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1284 else
Daniel Jasperbbc84152013-01-29 11:27:30 +00001285 Current.TotalLength =
1286 Current.Parent->TotalLength + Current.FormatTok.TokenLength +
1287 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001288 if (!Current.Children.empty())
1289 calculateExtraInformation(Current.Children[0]);
1290 }
1291
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001292 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001293 AnnotatingParser Parser(Line.First);
1294 Line.Type = Parser.parseLine();
1295 if (Line.Type == LT_Invalid)
1296 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001297
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001298 bool LookForFunctionName = Line.MustBeDeclaration;
1299 determineTokenTypes(Line.First, /*IsExpression=*/ false,
1300 LookForFunctionName);
Daniel Jasperda16db32013-01-07 10:48:50 +00001301
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001302 if (Line.First.Type == TT_ObjCMethodSpecifier)
1303 Line.Type = LT_ObjCMethodDecl;
1304 else if (Line.First.Type == TT_ObjCDecl)
1305 Line.Type = LT_ObjCDecl;
1306 else if (Line.First.Type == TT_ObjCProperty)
1307 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001308
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001309 Line.First.SpaceRequiredBefore = true;
1310 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1311 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001312
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001313 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001314 if (!Line.First.Children.empty())
1315 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001316 }
1317
1318private:
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001319 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression,
1320 bool LookForFunctionName) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001321 if (getPrecedence(Current) == prec::Assignment) {
1322 IsExpression = true;
1323 AnnotatedToken *Previous = Current.Parent;
1324 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001325 if (Previous->Type == TT_BinaryOperator &&
1326 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001327 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001328 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001329 Previous = Previous->Parent;
1330 }
1331 }
1332 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001333 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1334 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001335 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001336
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001337 if (Current.Type == TT_Unknown) {
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001338 if (LookForFunctionName && Current.is(tok::l_paren)) {
1339 findFunctionName(&Current);
1340 LookForFunctionName = false;
1341 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001342 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001343 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1344 Current.is(tok::caret)) {
1345 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001346 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1347 Current.Type = determineIncrementUsage(Current);
1348 } else if (Current.is(tok::exclaim)) {
1349 Current.Type = TT_UnaryOperator;
1350 } else if (isBinaryOperator(Current)) {
1351 Current.Type = TT_BinaryOperator;
1352 } else if (Current.is(tok::comment)) {
1353 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1354 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001355 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001356 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001357 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001358 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001359 } else if (Current.is(tok::r_paren) &&
1360 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001361 Current.Parent->Type == TT_TemplateCloser) &&
1362 (Current.Children.empty() ||
1363 (Current.Children[0].isNot(tok::equal) &&
1364 Current.Children[0].isNot(tok::semi) &&
1365 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001366 // FIXME: We need to get smarter and understand more cases of casts.
1367 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001368 } else if (Current.is(tok::at) && Current.Children.size()) {
1369 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1370 case tok::objc_interface:
1371 case tok::objc_implementation:
1372 case tok::objc_protocol:
1373 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001374 break;
1375 case tok::objc_property:
1376 Current.Type = TT_ObjCProperty;
1377 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001378 default:
1379 break;
1380 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001381 }
1382 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001383
1384 if (!Current.Children.empty())
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001385 determineTokenTypes(Current.Children[0], IsExpression,
1386 LookForFunctionName);
1387 }
1388
1389 /// \brief Starting from \p Current, this searches backwards for an
1390 /// identifier which could be the start of a function name and marks it.
1391 void findFunctionName(AnnotatedToken *Current) {
1392 AnnotatedToken *Parent = Current->Parent;
1393 while (Parent != NULL && Parent->Parent != NULL) {
1394 if (Parent->is(tok::identifier) &&
1395 (Parent->Parent->is(tok::identifier) ||
1396 Parent->Parent->Type == TT_PointerOrReference ||
1397 Parent->Parent->Type == TT_TemplateCloser)) {
1398 Parent->Type = TT_StartOfName;
1399 break;
1400 }
1401 Parent = Parent->Parent;
1402 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001403 }
1404
Daniel Jasper71945272013-01-15 14:27:39 +00001405 /// \brief Returns the previous token ignoring comments.
1406 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1407 const AnnotatedToken *PrevToken = Tok.Parent;
1408 while (PrevToken != NULL && PrevToken->is(tok::comment))
1409 PrevToken = PrevToken->Parent;
1410 return PrevToken;
1411 }
1412
1413 /// \brief Returns the next token ignoring comments.
1414 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1415 if (Tok.Children.empty())
1416 return NULL;
1417 const AnnotatedToken *NextToken = &Tok.Children[0];
1418 while (NextToken->is(tok::comment)) {
1419 if (NextToken->Children.empty())
1420 return NULL;
1421 NextToken = &NextToken->Children[0];
1422 }
1423 return NextToken;
1424 }
1425
1426 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasperbbc84152013-01-29 11:27:30 +00001427 TokenType
1428 determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001429 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1430 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001431 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001432
1433 const AnnotatedToken *NextToken = getNextToken(Tok);
1434 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001435 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001436
Daniel Jasper0b820602013-01-22 11:46:26 +00001437 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1438 return TT_PointerOrReference;
1439
Daniel Jasper71945272013-01-15 14:27:39 +00001440 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1441 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1442 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1443 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001444 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001445 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001446
Daniel Jasper71945272013-01-15 14:27:39 +00001447 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1448 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1449 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1450 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1451 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1452 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1453 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001454 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001455
Daniel Jasper71945272013-01-15 14:27:39 +00001456 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1457 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001458 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001459
Daniel Jasper426702d2012-12-05 07:51:39 +00001460 // It is very unlikely that we are going to find a pointer or reference type
1461 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001462 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001463 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001464
Daniel Jasperda16db32013-01-07 10:48:50 +00001465 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001466 }
1467
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001468 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001469 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1470 if (PrevToken == NULL)
1471 return TT_UnaryOperator;
1472
Daniel Jasper8dd40472012-12-21 09:41:31 +00001473 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001474 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1475 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1476 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1477 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1478 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001479 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001480
1481 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001482 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001483 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001484
1485 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001486 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001487 }
1488
1489 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001490 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001491 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1492 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001493 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001494 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1495 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001496 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001497
Daniel Jasperda16db32013-01-07 10:48:50 +00001498 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001499 }
1500
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001501 bool spaceRequiredBetween(const AnnotatedToken &Left,
1502 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001503 if (Right.is(tok::hashhash))
1504 return Left.is(tok::hash);
1505 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1506 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001507 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1508 return false;
Nico Webera6087752013-01-10 20:12:55 +00001509 if (Right.is(tok::less) &&
1510 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001511 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001512 return true;
1513 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1514 return false;
1515 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1516 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001517 if (Left.is(tok::at) &&
1518 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1519 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001520 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1521 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001522 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001523 if (Left.is(tok::coloncolon))
1524 return false;
1525 if (Right.is(tok::coloncolon))
1526 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001527 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1528 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001529 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001530 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001531 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1532 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001534 return Right.FormatTok.Tok.isLiteral() ||
1535 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001536 if (Right.is(tok::star) && Left.is(tok::l_paren))
1537 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001538 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1539 return false;
1540 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001541 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001542 if (Left.is(tok::period) || Right.is(tok::period))
1543 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001544 if (Left.is(tok::colon))
1545 return Left.Type != TT_ObjCMethodExpr;
1546 if (Right.is(tok::colon))
1547 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001548 if (Left.is(tok::l_paren))
1549 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001550 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001551 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001552 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001553 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001554 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1555 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001556 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001557 if (Left.is(tok::at) &&
1558 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001559 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001560 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1561 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001562 return true;
1563 }
1564
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001565 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001566 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001567 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1568 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001569 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001570 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001571 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001572 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001573 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001575 // Don't space between ')' and <id>
1576 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001577 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001578 // Don't space between ':' and '('
1579 return false;
1580 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001581 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001582 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1583 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001584
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001585 if (Tok.Parent->is(tok::comma))
1586 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001587 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001588 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001589 if (Tok.Type == TT_OverloadedOperator)
1590 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001591 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001592 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001593 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001594 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001595 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001596 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001597 if (Tok.Parent->Type == TT_UnaryOperator ||
1598 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001599 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001600 if (Tok.Type == TT_UnaryOperator)
1601 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001602 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1603 (Tok.Parent->isNot(tok::colon) ||
1604 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001605 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1606 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001607 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1608 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001609 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001610 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001611 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001612 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001613 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001614 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001615 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001616 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001617 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001618 }
1619
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001620 bool canBreakBefore(const AnnotatedToken &Right) {
1621 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001622 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001623 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1624 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001625 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001626 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1627 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001628 // Don't break this identifier as ':' or identifier
1629 // before it will break.
1630 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001631 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1632 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001633 // Don't break at ':' if identifier before it can beak.
1634 return false;
1635 }
Daniel Jasperd36ef5e2013-01-28 15:40:20 +00001636 if (Right.Type == TT_StartOfName && Style.AllowReturnTypeOnItsOwnLine)
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001637 return true;
Nico Webera7252d82013-01-12 06:18:40 +00001638 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1639 return false;
1640 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1641 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001642 if (isObjCSelectorName(Right))
1643 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001644 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001645 return true;
Daniel Jasperca6623b2013-01-28 12:45:14 +00001646 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1647 return true;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001648 if (Left.Type == TT_RangeBasedForLoopColon)
1649 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001650 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperca6623b2013-01-28 12:45:14 +00001651 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1652 Left.is(tok::question))
Daniel Jasperd1926a32013-01-02 08:44:14 +00001653 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001654 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001655 return false;
1656
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001657 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001658 // We rely on MustBreakBefore being set correctly here as we should not
1659 // change the "binding" behavior of a comment.
1660 return false;
1661
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001662 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1663 // unless it is follow by ';', '{' or '='.
1664 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1665 Left.Parent->is(tok::r_paren))
1666 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1667 Right.isNot(tok::equal);
1668
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001669 // We only break before r_brace if there was a corresponding break before
1670 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1671 if (Right.is(tok::r_brace))
1672 return false;
1673
Daniel Jasper71945272013-01-15 14:27:39 +00001674 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001675 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001676 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1677 Left.is(tok::comma) || Right.is(tok::lessless) ||
1678 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001679 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1680 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001681 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1682 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001683 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1684 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001685 }
1686
Daniel Jasperf7935112012-12-03 18:12:45 +00001687 FormatStyle Style;
1688 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001689 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001690 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001691};
1692
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001693class LexerBasedFormatTokenSource : public FormatTokenSource {
1694public:
1695 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001696 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001697 IdentTable(Lex.getLangOpts()) {
1698 Lex.SetKeepWhitespaceMode(true);
1699 }
1700
1701 virtual FormatToken getNextToken() {
1702 if (GreaterStashed) {
1703 FormatTok.NewlinesBefore = 0;
1704 FormatTok.WhiteSpaceStart =
1705 FormatTok.Tok.getLocation().getLocWithOffset(1);
1706 FormatTok.WhiteSpaceLength = 0;
1707 GreaterStashed = false;
1708 return FormatTok;
1709 }
1710
1711 FormatTok = FormatToken();
1712 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001713 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001714 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001715 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1716 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001717
1718 // Consume and record whitespace until we find a significant token.
1719 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001720 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +00001721 FormatTok.HasUnescapedNewline =
1722 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001723 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1724
1725 if (FormatTok.Tok.is(tok::eof))
1726 return FormatTok;
1727 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001728 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001729 }
Manuel Klimekef920692013-01-07 07:56:50 +00001730
1731 // Now FormatTok is the next non-whitespace token.
1732 FormatTok.TokenLength = Text.size();
1733
Manuel Klimek1abf7892013-01-04 23:34:14 +00001734 // In case the token starts with escaped newlines, we want to
1735 // take them into account as whitespace - this pattern is quite frequent
1736 // in macro definitions.
1737 // FIXME: What do we want to do with other escaped spaces, and escaped
1738 // spaces or newlines in the middle of tokens?
1739 // FIXME: Add a more explicit test.
1740 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001741 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001742 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001743 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001744 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001745 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001746 }
1747
1748 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001749 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001750 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001751 FormatTok.Tok.setKind(Info.getTokenID());
1752 }
1753
1754 if (FormatTok.Tok.is(tok::greatergreater)) {
1755 FormatTok.Tok.setKind(tok::greater);
1756 GreaterStashed = true;
1757 }
1758
1759 return FormatTok;
1760 }
1761
1762private:
1763 FormatToken FormatTok;
1764 bool GreaterStashed;
1765 Lexer &Lex;
1766 SourceManager &SourceMgr;
1767 IdentifierTable IdentTable;
1768
1769 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001770 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001771 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1772 Tok.getLength());
1773 }
1774};
1775
Daniel Jasperf7935112012-12-03 18:12:45 +00001776class Formatter : public UnwrappedLineConsumer {
1777public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001778 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1779 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001780 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001781 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001782 Whitespaces(SourceMgr), Ranges(Ranges) {
1783 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001784
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001785 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001786
Daniel Jasperf7935112012-12-03 18:12:45 +00001787 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001788 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001789 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001790 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001791 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001792 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1793 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1794 Annotator.annotate();
1795 }
1796 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1797 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001798 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001799 const AnnotatedLine &TheLine = *I;
1800 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001801 unsigned Indent =
1802 formatFirstToken(TheLine.First, TheLine.Level,
1803 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001804 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001805 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001806 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001807 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001808 PreviousEndOfLineColumn = Formatter.format();
1809 } else {
1810 // If we did not reformat this unwrapped line, the column at the end of
1811 // the last token is unchanged - thus, we can calculate the end of the
1812 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001813 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001814 SourceMgr.getSpellingColumnNumber(
1815 TheLine.Last->FormatTok.Tok.getLocation()) +
1816 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001817 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001818 }
1819 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001820 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001821 }
1822
1823private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001824 /// \brief Tries to merge lines into one.
1825 ///
1826 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1827 /// if possible; note that \c I will be incremented when lines are merged.
1828 ///
1829 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001830 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001831 std::vector<AnnotatedLine>::iterator &I,
1832 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001833 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1834
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001835 // We can never merge stuff if there are trailing line comments.
1836 if (I->Last->Type == TT_LineComment)
1837 return;
1838
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001839 // Check whether the UnwrappedLine can be put onto a single line. If
1840 // so, this is bound to be the optimal solution (by definition) and we
1841 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001842 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001843 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001844 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001845
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001846 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001847 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001848
Daniel Jasper25837aa2013-01-14 14:14:23 +00001849 if (I->Last->is(tok::l_brace)) {
1850 tryMergeSimpleBlock(I, E, Limit);
1851 } else if (I->First.is(tok::kw_if)) {
1852 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001853 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1854 I->First.FormatTok.IsFirst)) {
1855 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001856 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001857 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001858 }
1859
Daniel Jasper39825ea2013-01-14 15:40:57 +00001860 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1861 std::vector<AnnotatedLine>::iterator E,
1862 unsigned Limit) {
1863 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001864 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1865 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001866 if (I + 2 != E && (I + 2)->InPPDirective &&
1867 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1868 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001869 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001870 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001871 join(Line, *(++I));
1872 }
1873
Daniel Jasper25837aa2013-01-14 14:14:23 +00001874 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1875 std::vector<AnnotatedLine>::iterator E,
1876 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001877 if (!Style.AllowShortIfStatementsOnASingleLine)
1878 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001879 if ((I + 1)->InPPDirective != I->InPPDirective ||
1880 ((I + 1)->InPPDirective &&
1881 (I + 1)->First.FormatTok.HasUnescapedNewline))
1882 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001883 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001884 if (Line.Last->isNot(tok::r_paren))
1885 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001886 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001887 return;
1888 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1889 return;
1890 // Only inline simple if's (no nested if or else).
1891 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1892 return;
1893 join(Line, *(++I));
1894 }
1895
1896 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001897 std::vector<AnnotatedLine>::iterator E,
1898 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001899 // First, check that the current line allows merging. This is the case if
1900 // we're not in a control flow statement and the last token is an opening
1901 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001902 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001903 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001904 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1905 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1906 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1907 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001908 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001909 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1910 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001911 if (!AllowedTokens)
1912 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001913
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001914 AnnotatedToken *Tok = &(I + 1)->First;
1915 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1916 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1917 Tok->SpaceRequiredBefore = false;
1918 join(Line, *(I + 1));
1919 I += 1;
1920 } else {
1921 // Check that we still have three lines and they fit into the limit.
1922 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1923 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001924 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001925
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001926 // Second, check that the next line does not contain any braces - if it
1927 // does, readability declines when putting it into a single line.
1928 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1929 return;
1930 do {
1931 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1932 return;
1933 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1934 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001935
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001936 // Last, check that the third line contains a single closing brace.
1937 Tok = &(I + 2)->First;
1938 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1939 Tok->MustBreakBefore)
1940 return;
1941
1942 join(Line, *(I + 1));
1943 join(Line, *(I + 2));
1944 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001945 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001946 }
1947
1948 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1949 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001950 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1951 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001952 }
1953
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001954 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1955 A.Last->Children.push_back(B.First);
1956 while (!A.Last->Children.empty()) {
1957 A.Last->Children[0].Parent = A.Last;
1958 A.Last = &A.Last->Children[0];
1959 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001960 }
1961
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001962 bool touchesRanges(const AnnotatedLine &TheLine) {
1963 const FormatToken *First = &TheLine.First.FormatTok;
1964 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001965 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001966 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001967 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001968 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1969 Ranges[i].getBegin()) &&
1970 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1971 LineRange.getBegin()))
1972 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001973 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001974 return false;
1975 }
1976
1977 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001978 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001979 }
1980
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001981 /// \brief Add a new line and the required indent before the first Token
1982 /// of the \c UnwrappedLine if there was no structural parsing error.
1983 /// Returns the indent level of the \c UnwrappedLine.
1984 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1985 bool InPPDirective,
1986 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001987 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001988 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1989 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1990
Daniel Jasperbbc84152013-01-29 11:27:30 +00001991 unsigned Newlines =
1992 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001993 if (Newlines == 0 && !Tok.IsFirst)
1994 Newlines = 1;
1995 unsigned Indent = Level * 2;
1996
1997 bool IsAccessModifier = false;
1998 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1999 RootToken.is(tok::kw_private))
2000 IsAccessModifier = true;
2001 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
2002 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
2003 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
2004 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
2005 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
2006 IsAccessModifier = true;
2007
2008 if (IsAccessModifier &&
2009 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
2010 Indent += Style.AccessModifierOffset;
2011 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002012 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002013 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002014 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
2015 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002016 }
2017 return Indent;
2018 }
2019
Alexander Kornienko116ba682013-01-14 11:34:14 +00002020 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00002021 FormatStyle Style;
2022 Lexer &Lex;
2023 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002024 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00002025 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00002026 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00002027 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00002028};
2029
Daniel Jasperbbc84152013-01-29 11:27:30 +00002030tooling::Replacements
2031reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
2032 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002033 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00002034 OwningPtr<DiagnosticConsumer> DiagPrinter;
2035 if (DiagClient == 0) {
2036 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
2037 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
2038 DiagClient = DiagPrinter.get();
2039 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002040 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002041 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002042 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002043 Diagnostics.setSourceManager(&SourceMgr);
2044 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002045 return formatter.format();
2046}
2047
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002048LangOptions getFormattingLangOpts() {
2049 LangOptions LangOpts;
2050 LangOpts.CPlusPlus = 1;
2051 LangOpts.CPlusPlus11 = 1;
2052 LangOpts.Bool = 1;
2053 LangOpts.ObjC1 = 1;
2054 LangOpts.ObjC2 = 1;
2055 return LangOpts;
2056}
2057
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002058} // namespace format
2059} // namespace clang