blob: 81c8309ef9d13fe9cd5557ba573362fbe85bd972 [file] [log] [blame]
Daniel Jasperbac016b2012-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 Klimekca547db2013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimekca547db2013-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 Jasperbac016b2012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasper71607512013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek407a31a2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Weberbcfdd262013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Weber70848232013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper83f25ba2013-01-28 15:16:31 +000053 TT_RangeBasedForLoopColon,
54 TT_StartOfName,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000055 TT_TemplateCloser,
56 TT_TemplateOpener,
57 TT_TrailingUnaryOperator,
58 TT_UnaryOperator,
59 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000060};
61
62enum LineType {
63 LT_Invalid,
64 LT_Other,
Daniel Jasper32983272013-01-22 14:28:24 +000065 LT_BuilderTypeCall,
Daniel Jasper71607512013-01-07 10:48:50 +000066 LT_PreprocessorDirective,
67 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000068 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000069 LT_ObjCMethodDecl,
70 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000071};
72
Daniel Jasper26f7e782013-01-08 14:56:18 +000073class AnnotatedToken {
74public:
Daniel Jasperdcc2a622013-01-18 08:44:07 +000075 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000076 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
77 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper986e17f2013-01-28 07:35:34 +000078 ClosesTemplateDeclaration(false), MatchingParen(NULL),
79 ParameterCount(1), Parent(NULL) {
80 }
Daniel Jasper26f7e782013-01-08 14:56:18 +000081
Daniel Jasperfeb18f52013-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 Jasper26f7e782013-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 Jasperbac016b2012-12-03 18:12:45 +000091 TokenType Type;
92
Daniel Jasperbac016b2012-12-03 18:12:45 +000093 bool SpaceRequiredBefore;
94 bool CanBreakBefore;
95 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000096
97 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000098
Daniel Jasper0df6acd2013-01-16 14:59:02 +000099 AnnotatedToken *MatchingParen;
100
Daniel Jasper986e17f2013-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 Jasper3f8cdbf2013-01-16 10:41:46 +0000108 /// \brief The total length of the line up to and including this token.
109 unsigned TotalLength;
110
Daniel Jasperadc6aba2013-01-29 15:03:01 +0000111 /// \brief Penalty for inserting a line break before this token.
112 unsigned SplitPenalty;
113
Daniel Jasper26f7e782013-01-08 14:56:18 +0000114 std::vector<AnnotatedToken> Children;
115 AnnotatedToken *Parent;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000116
117 const AnnotatedToken *getPreviousNoneComment() const {
118 AnnotatedToken *Tok = Parent;
119 while (Tok != NULL && Tok->is(tok::comment))
120 Tok = Tok->Parent;
121 return Tok;
122 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000123};
124
Daniel Jasper995e8202013-01-14 13:08:07 +0000125class AnnotatedLine {
126public:
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000127 AnnotatedLine(const UnwrappedLine &Line)
128 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek70b03f42013-01-23 09:32:48 +0000129 InPPDirective(Line.InPPDirective),
130 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000131 assert(!Line.Tokens.empty());
132 AnnotatedToken *Current = &First;
133 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
134 E = Line.Tokens.end();
135 I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000136 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000137 Current->Children[0].Parent = Current;
138 Current = &Current->Children[0];
139 }
140 Last = Current;
141 }
142 AnnotatedLine(const AnnotatedLine &Other)
143 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek70b03f42013-01-23 09:32:48 +0000144 InPPDirective(Other.InPPDirective),
145 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000146 Last = &First;
147 while (!Last->Children.empty()) {
148 Last->Children[0].Parent = Last;
149 Last = &Last->Children[0];
150 }
151 }
152
Daniel Jasper995e8202013-01-14 13:08:07 +0000153 AnnotatedToken First;
154 AnnotatedToken *Last;
155
156 LineType Type;
157 unsigned Level;
158 bool InPPDirective;
Manuel Klimek70b03f42013-01-23 09:32:48 +0000159 bool MustBeDeclaration;
Daniel Jasper995e8202013-01-14 13:08:07 +0000160};
161
Daniel Jasper26f7e782013-01-08 14:56:18 +0000162static prec::Level getPrecedence(const AnnotatedToken &Tok) {
163 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +0000164}
165
Daniel Jasperae8699b2013-01-28 09:35:24 +0000166bool isBinaryOperator(const AnnotatedToken &Tok) {
167 // Comma is a binary operator, but does not behave as such wrt. formatting.
168 return getPrecedence(Tok) > prec::Comma;
169}
170
Daniel Jasperbac016b2012-12-03 18:12:45 +0000171FormatStyle getLLVMStyle() {
172 FormatStyle LLVMStyle;
173 LLVMStyle.ColumnLimit = 80;
174 LLVMStyle.MaxEmptyLinesToKeep = 1;
175 LLVMStyle.PointerAndReferenceBindToType = false;
176 LLVMStyle.AccessModifierOffset = -2;
177 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000178 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000179 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000180 LLVMStyle.BinPackParameters = true;
Daniel Jasperf1579602013-01-29 16:03:49 +0000181 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +0000182 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000183 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000184 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000185 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186 return LLVMStyle;
187}
188
189FormatStyle getGoogleStyle() {
190 FormatStyle GoogleStyle;
191 GoogleStyle.ColumnLimit = 80;
192 GoogleStyle.MaxEmptyLinesToKeep = 1;
193 GoogleStyle.PointerAndReferenceBindToType = true;
194 GoogleStyle.AccessModifierOffset = -1;
195 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000196 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000197 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000198 GoogleStyle.BinPackParameters = false;
Daniel Jasperf1579602013-01-29 16:03:49 +0000199 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd75ff642013-01-28 15:40:20 +0000200 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000201 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +0000202 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000203 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000204 return GoogleStyle;
205}
206
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000207FormatStyle getChromiumStyle() {
208 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf1579602013-01-29 16:03:49 +0000209 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasperf40fb4b2013-01-29 15:19:38 +0000210 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000211 return ChromiumStyle;
212}
213
Daniel Jasperbac016b2012-12-03 18:12:45 +0000214struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000215 unsigned PenaltyIndentLevel;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000216 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000217};
218
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000219/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000220///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000221/// This includes special handling for certain constructs, e.g. the alignment of
222/// trailing line comments.
223class WhitespaceManager {
224public:
225 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
226
227 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
228 /// each \c AnnotatedToken.
229 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
230 unsigned Spaces, unsigned WhitespaceStartColumn,
231 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000232 // 2+ newlines mean an empty line separating logic scopes.
233 if (NewLines >= 2)
234 alignComments();
235
236 // Align line comments if they are trailing or if they continue other
237 // trailing comments.
238 if (Tok.Type == TT_LineComment &&
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000239 (Tok.Parent != NULL || !Comments.empty())) {
240 if (Style.ColumnLimit >=
241 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
242 Comments.push_back(StoredComment());
243 Comments.back().Tok = Tok.FormatTok;
244 Comments.back().Spaces = Spaces;
245 Comments.back().NewLines = NewLines;
246 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000247 Comments.back().MaxColumn =
248 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000249 return;
250 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000251 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000252
253 // If this line does not have a trailing comment, align the stored comments.
254 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
255 alignComments();
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000256 storeReplacement(Tok.FormatTok,
257 std::string(NewLines, '\n') + std::string(Spaces, ' '));
258 }
259
260 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
261 /// backslashes to escape newlines inside a preprocessor directive.
262 ///
263 /// This function and \c replaceWhitespace have the same behavior if
264 /// \c Newlines == 0.
265 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
266 unsigned Spaces, unsigned WhitespaceStartColumn,
267 const FormatStyle &Style) {
268 std::string NewLineText;
269 if (NewLines > 0) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000270 unsigned Offset =
271 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000272 for (unsigned i = 0; i < NewLines; ++i) {
273 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
274 NewLineText += "\\\n";
275 Offset = 0;
276 }
277 }
278 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
279 }
280
281 /// \brief Returns all the \c Replacements created during formatting.
282 const tooling::Replacements &generateReplacements() {
283 alignComments();
284 return Replaces;
285 }
286
287private:
288 /// \brief Structure to store a comment for later layout and alignment.
289 struct StoredComment {
290 FormatToken Tok;
291 unsigned MinColumn;
292 unsigned MaxColumn;
293 unsigned NewLines;
294 unsigned Spaces;
295 };
296 SmallVector<StoredComment, 16> Comments;
297 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
298
299 /// \brief Try to align all stashed comments.
300 void alignComments() {
301 unsigned MinColumn = 0;
302 unsigned MaxColumn = UINT_MAX;
303 comment_iterator Start = Comments.begin();
304 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
305 ++I) {
306 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
307 alignComments(Start, I, MinColumn);
308 MinColumn = I->MinColumn;
309 MaxColumn = I->MaxColumn;
310 Start = I;
311 } else {
312 MinColumn = std::max(MinColumn, I->MinColumn);
313 MaxColumn = std::min(MaxColumn, I->MaxColumn);
314 }
315 }
316 alignComments(Start, Comments.end(), MinColumn);
317 Comments.clear();
318 }
319
320 /// \brief Put all the comments between \p I and \p E into \p Column.
321 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
322 while (I != E) {
323 unsigned Spaces = I->Spaces + Column - I->MinColumn;
324 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
325 std::string(Spaces, ' '));
326 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000327 }
328 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000329
330 /// \brief Stores \p Text as the replacement for the whitespace in front of
331 /// \p Tok.
332 void storeReplacement(const FormatToken &Tok, const std::string Text) {
333 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
334 Tok.WhiteSpaceLength, Text));
335 }
336
337 SourceManager &SourceMgr;
338 tooling::Replacements Replaces;
339};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000340
Nico Webere8ccc812013-01-12 22:48:47 +0000341/// \brief Returns if a token is an Objective-C selector name.
342///
Nico Weberea865632013-01-12 22:51:13 +0000343/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Webere8ccc812013-01-12 22:48:47 +0000344static bool isObjCSelectorName(const AnnotatedToken &Tok) {
345 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
346 Tok.Children[0].is(tok::colon) &&
347 Tok.Children[0].Type == TT_ObjCMethodExpr;
348}
349
Daniel Jasperbac016b2012-12-03 18:12:45 +0000350class UnwrappedLineFormatter {
351public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000352 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000353 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000354 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000355 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000356 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000357 FirstIndent(FirstIndent), RootToken(RootToken),
358 Whitespaces(Whitespaces) {
Daniel Jasperc79afda2013-01-18 10:56:38 +0000359 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000360 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000361 }
362
Manuel Klimekd4397b92013-01-04 23:34:14 +0000363 /// \brief Formats an \c UnwrappedLine.
364 ///
365 /// \returns The column after the last token in the last line of the
366 /// \c UnwrappedLine.
367 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000368 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000369 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000370 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000371 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000372 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasper2e603772013-01-29 11:21:01 +0000373 State.VariablePos = 0;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000374 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000375
Manuel Klimekca547db2013-01-16 14:55:28 +0000376 DEBUG({
377 DebugTokenState(*State.NextToken);
378 });
379
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000380 // The first token has already been indented and thus consumed.
381 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000382
383 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000384 while (State.NextToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000385 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
386 // Calculating the column is important for aligning trailing comments.
387 // FIXME: This does not seem to happen in conjunction with escaped
388 // newlines. If it does, fix!
389 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
390 State.NextToken->FormatTok.TokenLength;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000391 State.NextToken = State.NextToken->Children.empty()
392 ? NULL : &State.NextToken->Children[0];
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000393 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000394 addTokenToState(false, false, State);
395 } else {
396 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
397 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimekca547db2013-01-16 14:55:28 +0000398 DEBUG({
399 if (Break < NoBreak)
400 llvm::errs() << "\n";
401 else
402 llvm::errs() << " ";
403 llvm::errs() << "<";
404 DebugPenalty(Break, Break < NoBreak);
405 llvm::errs() << "/";
406 DebugPenalty(NoBreak, !(Break < NoBreak));
407 llvm::errs() << "> ";
408 DebugTokenState(*State.NextToken);
409 });
Daniel Jasper1321eb52012-12-18 21:05:13 +0000410 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000411 if (State.NextToken != NULL &&
412 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
413 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000414 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000415 State.Stack.back().BreakAfterComma = true;
416 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000417 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000418 }
Manuel Klimekca547db2013-01-16 14:55:28 +0000419 DEBUG(llvm::errs() << "\n");
Manuel Klimekd4397b92013-01-04 23:34:14 +0000420 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000421 }
422
423private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000424 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
425 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000426 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
427 Tok.getLength());
Manuel Klimekca547db2013-01-16 14:55:28 +0000428 llvm::errs();
429 }
430
431 void DebugPenalty(unsigned Penalty, bool Winner) {
432 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
433 if (Penalty == UINT_MAX)
434 llvm::errs() << "MAX";
435 else
436 llvm::errs() << Penalty;
437 llvm::errs().resetColor();
438 }
439
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000440 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000441 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jasperf39c8852013-01-23 16:58:21 +0000442 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000443 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000444 BreakAfterComma(false), HasMultiParameterLine(false) {
445 }
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000446
Daniel Jasperbac016b2012-12-03 18:12:45 +0000447 /// \brief The position to which a specific parenthesis level needs to be
448 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000449 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000450
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000451 /// \brief The position of the last space on each level.
452 ///
453 /// Used e.g. to break like:
454 /// functionCall(Parameter, otherCall(
455 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000456 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000457
Daniel Jasperf39c8852013-01-23 16:58:21 +0000458 /// \brief This is the column of the first token after an assignment.
459 unsigned AssignmentColumn;
460
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000461 /// \brief The position the first "<<" operator encountered on each level.
462 ///
463 /// Used to align "<<" operators. 0 if no such operator has been encountered
464 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000465 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000466
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000467 /// \brief Whether a newline needs to be inserted before the block's closing
468 /// brace.
469 ///
470 /// We only want to insert a newline before the closing brace if there also
471 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000472 bool BreakBeforeClosingBrace;
473
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000474 /// \brief The column of a \c ? in a conditional expression;
475 unsigned QuestionColumn;
476
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000477 bool BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000478 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000479
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000480 bool operator<(const ParenState &Other) const {
481 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000482 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000483 if (LastSpace != Other.LastSpace)
484 return LastSpace < Other.LastSpace;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000485 if (AssignmentColumn != Other.AssignmentColumn)
486 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000487 if (FirstLessLess != Other.FirstLessLess)
488 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000489 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
490 return BreakBeforeClosingBrace;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000491 if (QuestionColumn != Other.QuestionColumn)
492 return QuestionColumn < Other.QuestionColumn;
Daniel Jasperb3123142013-01-12 07:36:22 +0000493 if (BreakAfterComma != Other.BreakAfterComma)
494 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000495 if (HasMultiParameterLine != Other.HasMultiParameterLine)
496 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000497 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000498 }
499 };
500
501 /// \brief The current state when indenting a unwrapped line.
502 ///
503 /// As the indenting tries different combinations this is copied by value.
504 struct LineState {
505 /// \brief The number of used columns in the current line.
506 unsigned Column;
507
508 /// \brief The token that needs to be next formatted.
509 const AnnotatedToken *NextToken;
510
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000511 /// \brief The column of the first variable name in a variable declaration.
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000512 ///
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000513 /// Used to align further variables if necessary.
Daniel Jasper2e603772013-01-29 11:21:01 +0000514 unsigned VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000515
516 /// \brief \c true if this line contains a continued for-loop section.
517 bool LineContainsContinuedForLoopSection;
518
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000519 /// \brief A stack keeping track of properties applying to parenthesis
520 /// levels.
521 std::vector<ParenState> Stack;
522
523 /// \brief Comparison operator to be able to used \c LineState in \c map.
524 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000525 if (Other.NextToken != NextToken)
526 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000527 if (Other.Column != Column)
528 return Other.Column > Column;
Daniel Jasper2e603772013-01-29 11:21:01 +0000529 if (Other.VariablePos != VariablePos)
530 return Other.VariablePos < VariablePos;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000531 if (Other.LineContainsContinuedForLoopSection !=
532 LineContainsContinuedForLoopSection)
533 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000534 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000535 }
536 };
537
Daniel Jasper20409152012-12-04 14:54:30 +0000538 /// \brief Appends the next token to \p State and updates information
539 /// necessary for indentation.
540 ///
541 /// Puts the token on the current line if \p Newline is \c true and adds a
542 /// line break and necessary indentation otherwise.
543 ///
544 /// If \p DryRun is \c false, also creates and stores the required
545 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000546 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000547 const AnnotatedToken &Current = *State.NextToken;
548 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000549 assert(State.Stack.size());
550 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000551
552 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000553 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000554 if (Current.is(tok::r_brace)) {
555 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000556 } else if (Current.is(tok::string_literal) &&
557 Previous.is(tok::string_literal)) {
558 State.Column = State.Column - Previous.FormatTok.TokenLength;
559 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000560 State.Stack[ParenLevel].FirstLessLess != 0) {
561 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000562 } else if (ParenLevel != 0 &&
Daniel Jasper5f2173e2013-01-28 07:43:15 +0000563 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000564 Current.is(tok::period) || Current.is(tok::arrow) ||
565 Current.is(tok::question))) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000566 // Indent and extra 4 spaces after if we know the current expression is
567 // continued. Don't do that on the top level, as we already indent 4
568 // there.
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000569 State.Column = std::max(State.Stack.back().LastSpace,
570 State.Stack.back().Indent) + 4;
571 } else if (Current.Type == TT_ConditionalExpr) {
572 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper2e603772013-01-29 11:21:01 +0000573 } else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
574 ((RootToken.is(tok::kw_for) && ParenLevel == 1) ||
575 ParenLevel == 0)) {
576 State.Column = State.VariablePos;
Daniel Jasper83f25ba2013-01-28 15:16:31 +0000577 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
578 Current.Type == TT_StartOfName) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000579 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperf39c8852013-01-23 16:58:21 +0000580 } else if (Previous.Type == TT_BinaryOperator &&
581 State.Stack.back().AssignmentColumn != 0) {
582 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000583 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000584 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000585 }
586
Daniel Jasper26f7e782013-01-08 14:56:18 +0000587 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000588 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000589
Manuel Klimek060143e2013-01-02 18:33:23 +0000590 if (!DryRun) {
591 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000592 Whitespaces.replaceWhitespace(Current, 1, State.Column,
593 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000594 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000595 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
596 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000597 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000598
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000599 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000600 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000601 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000602 } else {
Daniel Jasper2e603772013-01-29 11:21:01 +0000603 if (Current.is(tok::equal) &&
604 (RootToken.is(tok::kw_for) || ParenLevel == 0))
605 State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000606
Daniel Jasper26f7e782013-01-08 14:56:18 +0000607 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
608 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000609 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000610
Daniel Jasperbac016b2012-12-03 18:12:45 +0000611 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000612 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000613
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000614 // FIXME: Do we need to do this for assignments nested in other
615 // expressions?
616 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000617 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000618 Previous.is(tok::kw_return)))
Daniel Jasperf39c8852013-01-23 16:58:21 +0000619 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000620 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000621 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000622 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimek86721d22013-01-22 16:31:55 +0000623 if (Current.getPreviousNoneComment() != NULL &&
624 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000625 Current.isNot(tok::comment))
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000626 State.Stack[ParenLevel].HasMultiParameterLine = true;
627
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000628 State.Column += Spaces;
Daniel Jaspere438bac2013-01-23 20:41:06 +0000629 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
630 // Treat the condition inside an if as if it was a second function
631 // parameter, i.e. let nested calls have an indent of 4.
632 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper3499dda2013-01-25 15:43:32 +0000633 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jaspere438bac2013-01-23 20:41:06 +0000634 // Top-level spaces are exempt as that mostly leads to better results.
635 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000636 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper02b771e2013-01-28 13:31:35 +0000637 Previous.Type == TT_ConditionalExpr ||
638 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasperae8699b2013-01-28 09:35:24 +0000639 getPrecedence(Previous) != prec::Assignment)
640 State.Stack.back().LastSpace = State.Column;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000641 else if (Previous.ParameterCount > 1 &&
642 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
643 Previous.Type == TT_TemplateOpener))
644 // If this function has multiple parameters, indent nested calls from
645 // the start of the first parameter.
646 State.Stack.back().LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000647 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000648
649 // If we break after an {, we should also break before the corresponding }.
650 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000651 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000652
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000653 if (!Style.BinPackParameters && Newline) {
654 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf1579602013-01-29 16:03:49 +0000655 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000656 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
657 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf1579602013-01-29 16:03:49 +0000658 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
659 Line.MustBeDeclaration))
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000660 State.Stack.back().BreakAfterComma = true;
Daniel Jasper2e603772013-01-29 11:21:01 +0000661
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000662 // Any break on this level means that the parent level has been broken
663 // and we need to avoid bin packing there.
664 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
665 State.Stack[i].BreakAfterComma = true;
666 }
667 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000668
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000669 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000670 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000671
Daniel Jasper20409152012-12-04 14:54:30 +0000672 /// \brief Mark the next token as consumed in \p State and modify its stacks
673 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000674 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000675 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000676 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000677
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000678 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
679 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +0000680 if (Current.is(tok::question))
681 State.Stack.back().QuestionColumn = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000682
Daniel Jaspercf225b62012-12-24 13:43:52 +0000683 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000684 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000685 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
686 Current.is(tok::l_brace) ||
687 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000688 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000689 if (Current.is(tok::l_brace)) {
690 // FIXME: This does not work with nested static initializers.
691 // Implement a better handling for static initializers and similar
692 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000693 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000694 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000695 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000696 }
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000697 State.Stack.push_back(ParenState(NewIndent,
698 State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000699 }
700
Daniel Jaspercf225b62012-12-24 13:43:52 +0000701 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000702 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000703 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
704 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
705 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000706 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000707 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000708
Daniel Jasper26f7e782013-01-08 14:56:18 +0000709 if (State.NextToken->Children.empty())
710 State.NextToken = NULL;
711 else
712 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000713
714 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000715 }
716
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000717 unsigned getColumnLimit() {
718 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
719 }
720
Daniel Jasperbac016b2012-12-03 18:12:45 +0000721 /// \brief Calculate the number of lines needed to format the remaining part
722 /// of the unwrapped line.
723 ///
724 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000725 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 /// added after the previous token.
727 ///
728 /// \param StopAt is used for optimization. If we can determine that we'll
729 /// definitely need at least \p StopAt additional lines, we already know of a
730 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000731 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000733 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 return 0;
735
Daniel Jasper26f7e782013-01-08 14:56:18 +0000736 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000737 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000738 if (NewLine && !State.NextToken->CanBreakBefore &&
739 !(State.NextToken->is(tok::r_brace) &&
740 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000742 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000743 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000744 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000745 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000746 State.LineContainsContinuedForLoopSection)
747 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000748 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000749 State.NextToken->isNot(tok::comment) &&
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000750 State.Stack.back().BreakAfterComma)
751 return UINT_MAX;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000752 // Trying to insert a parameter on a new line if there are already more than
753 // one parameter on the current line is bin packing.
754 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
755 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
756 return UINT_MAX;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000757 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
758 (State.NextToken->Parent->ClosesTemplateDeclaration &&
759 State.Stack.size() == 1)))
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000760 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000761
Daniel Jasper33182dd2012-12-05 14:57:28 +0000762 unsigned CurrentPenalty = 0;
Daniel Jasperae8699b2013-01-28 09:35:24 +0000763 if (NewLine)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000764 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasperadc6aba2013-01-29 15:03:01 +0000765 State.NextToken->SplitPenalty;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000766
Daniel Jasper20409152012-12-04 14:54:30 +0000767 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000768
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000769 // Exceeding column limit is bad, assign penalty.
770 if (State.Column > getColumnLimit()) {
771 unsigned ExcessCharacters = State.Column - getColumnLimit();
772 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
773 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000774
Daniel Jasperbac016b2012-12-03 18:12:45 +0000775 if (StopAt <= CurrentPenalty)
776 return UINT_MAX;
777 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000778 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000779 if (I != Memory.end()) {
780 // If this state has already been examined, we can safely return the
781 // previous result if we
782 // - have not hit the optimatization (and thus returned UINT_MAX) OR
783 // - are now computing for a smaller or equal StopAt.
784 unsigned SavedResult = I->second.first;
785 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000786 if (SavedResult != UINT_MAX)
787 return SavedResult + CurrentPenalty;
788 else if (StopAt <= SavedStopAt)
789 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000790 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000791
792 unsigned NoBreak = calcPenalty(State, false, StopAt);
793 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
794 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000795
796 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
797 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000798 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000799
800 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000801 }
802
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 FormatStyle Style;
804 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000805 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000806 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000807 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000808 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809
Daniel Jasper33182dd2012-12-05 14:57:28 +0000810 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000811 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000812 StateMap Memory;
813
Daniel Jasperbac016b2012-12-03 18:12:45 +0000814 OptimizationParameters Parameters;
815};
816
817/// \brief Determines extra information about the tokens comprising an
818/// \c UnwrappedLine.
819class TokenAnnotator {
820public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000821 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
822 AnnotatedLine &Line)
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000823 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {
824 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000825
826 /// \brief A parser that gathers additional information about tokens.
827 ///
828 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
829 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
830 /// into template parameter lists.
831 class AnnotatingParser {
832 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000833 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000834 : CurrentToken(&RootToken), KeywordVirtualFound(false),
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000835 ColonIsObjCMethodExpr(false), ColonIsForRangeExpr(false) {
836 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000837
Nico Weber6a21a552013-01-18 02:43:57 +0000838 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
839 struct ObjCSelectorRAII {
840 AnnotatingParser &P;
841 bool ColonWasObjCMethodExpr;
842
843 ObjCSelectorRAII(AnnotatingParser &P)
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000844 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {
845 }
Nico Weber6a21a552013-01-18 02:43:57 +0000846
847 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
848
849 void markStart(AnnotatedToken &Left) {
850 P.ColonIsObjCMethodExpr = true;
851 Left.Type = TT_ObjCMethodExpr;
852 }
853
854 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
855 };
856
Daniel Jasper20409152012-12-04 14:54:30 +0000857 bool parseAngle() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000858 if (CurrentToken == NULL)
859 return false;
860 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000861 while (CurrentToken != NULL) {
862 if (CurrentToken->is(tok::greater)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000863 Left->MatchingParen = CurrentToken;
864 CurrentToken->MatchingParen = Left;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000865 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000866 next();
867 return true;
868 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000869 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
870 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000871 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000872 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
873 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000874 return false;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000875 if (CurrentToken->is(tok::comma))
876 ++Left->ParameterCount;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000877 if (!consumeToken())
878 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000879 }
880 return false;
881 }
882
Nico Weber5096a442013-01-17 17:17:19 +0000883 bool parseParens(bool LookForDecls = false) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000884 if (CurrentToken == NULL)
885 return false;
Nico Weber6a21a552013-01-18 02:43:57 +0000886 bool StartsObjCMethodExpr = false;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000887 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber6a21a552013-01-18 02:43:57 +0000888 if (CurrentToken->is(tok::caret)) {
889 // ^( starts a block.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000890 Left->Type = TT_ObjCBlockLParen;
Nico Weber6a21a552013-01-18 02:43:57 +0000891 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
892 // @selector( starts a selector.
893 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
894 MaybeSel->Parent->is(tok::at)) {
895 StartsObjCMethodExpr = true;
896 }
897 }
898
899 ObjCSelectorRAII objCSelector(*this);
900 if (StartsObjCMethodExpr)
901 objCSelector.markStart(*Left);
902
Daniel Jasper26f7e782013-01-08 14:56:18 +0000903 while (CurrentToken != NULL) {
Nico Weber5096a442013-01-17 17:17:19 +0000904 // LookForDecls is set when "if (" has been seen. Check for
905 // 'identifier' '*' 'identifier' followed by not '=' -- this
906 // '*' has to be a binary operator but determineStarAmpUsage() will
907 // categorize it as an unary operator, so set the right type here.
908 if (LookForDecls && !CurrentToken->Children.empty()) {
909 AnnotatedToken &Prev = *CurrentToken->Parent;
910 AnnotatedToken &Next = CurrentToken->Children[0];
911 if (Prev.Parent->is(tok::identifier) &&
912 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
913 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
914 Prev.Type = TT_BinaryOperator;
915 LookForDecls = false;
916 }
917 }
918
Daniel Jasper26f7e782013-01-08 14:56:18 +0000919 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000920 Left->MatchingParen = CurrentToken;
921 CurrentToken->MatchingParen = Left;
Nico Weber6a21a552013-01-18 02:43:57 +0000922
923 if (StartsObjCMethodExpr)
924 objCSelector.markEnd(*CurrentToken);
925
Daniel Jasperbac016b2012-12-03 18:12:45 +0000926 next();
927 return true;
928 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000929 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000930 return false;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000931 if (CurrentToken->is(tok::comma))
932 ++Left->ParameterCount;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000933 if (!consumeToken())
934 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000935 }
936 return false;
937 }
938
Daniel Jasper20409152012-12-04 14:54:30 +0000939 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000940 if (!CurrentToken)
941 return false;
942
943 // A '[' could be an index subscript (after an indentifier or after
944 // ')' or ']'), or it could be the start of an Objective-C method
945 // expression.
Nico Weber3f29fbb2013-01-21 19:29:31 +0000946 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weberbcfdd262013-01-12 06:18:40 +0000947 bool StartsObjCMethodExpr =
Nico Weber3f29fbb2013-01-21 19:29:31 +0000948 !Left->Parent || Left->Parent->is(tok::colon) ||
949 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
950 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
Daniel Jasper1a1ce832013-01-29 11:27:30 +0000951 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(), true,
952 true) > prec::Unknown;
Nico Weberbcfdd262013-01-12 06:18:40 +0000953
Nico Weber6a21a552013-01-18 02:43:57 +0000954 ObjCSelectorRAII objCSelector(*this);
955 if (StartsObjCMethodExpr)
Nico Weber3f29fbb2013-01-21 19:29:31 +0000956 objCSelector.markStart(*Left);
Nico Weberbcfdd262013-01-12 06:18:40 +0000957
Daniel Jasper26f7e782013-01-08 14:56:18 +0000958 while (CurrentToken != NULL) {
959 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperffee1712013-01-22 11:46:26 +0000960 if (!CurrentToken->Children.empty() &&
961 CurrentToken->Children[0].is(tok::l_paren)) {
962 // An ObjC method call can't be followed by an open parenthesis.
963 // FIXME: Do we incorrectly label ":" with this?
964 StartsObjCMethodExpr = false;
965 Left->Type = TT_Unknown;
Daniel Jasper2e603772013-01-29 11:21:01 +0000966 }
Nico Weber6a21a552013-01-18 02:43:57 +0000967 if (StartsObjCMethodExpr)
968 objCSelector.markEnd(*CurrentToken);
Nico Weber05bf8272013-01-21 19:35:06 +0000969 Left->MatchingParen = CurrentToken;
970 CurrentToken->MatchingParen = Left;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000971 next();
972 return true;
973 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000974 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000975 return false;
Daniel Jasper986e17f2013-01-28 07:35:34 +0000976 if (CurrentToken->is(tok::comma))
977 ++Left->ParameterCount;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000978 if (!consumeToken())
979 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000980 }
981 return false;
982 }
983
Daniel Jasper700e7102013-01-10 09:26:47 +0000984 bool parseBrace() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000985 // Lines are fine to end with '{'.
986 if (CurrentToken == NULL)
987 return true;
988 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper700e7102013-01-10 09:26:47 +0000989 while (CurrentToken != NULL) {
990 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000991 Left->MatchingParen = CurrentToken;
992 CurrentToken->MatchingParen = Left;
Daniel Jasper700e7102013-01-10 09:26:47 +0000993 next();
994 return true;
995 }
996 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
997 return false;
998 if (!consumeToken())
999 return false;
1000 }
Daniel Jasper700e7102013-01-10 09:26:47 +00001001 return true;
1002 }
1003
Daniel Jasper20409152012-12-04 14:54:30 +00001004 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001005 while (CurrentToken != NULL) {
1006 if (CurrentToken->is(tok::colon)) {
1007 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001008 next();
1009 return true;
1010 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001011 if (!consumeToken())
1012 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001013 }
1014 return false;
1015 }
1016
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001017 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001018 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1019 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001020 next();
1021 if (!parseAngle())
1022 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001023 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001024 return true;
1025 }
1026 return false;
1027 }
1028
Daniel Jasper1f42f112013-01-04 18:52:56 +00001029 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001030 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001031 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001032 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +00001033 case tok::plus:
1034 case tok::minus:
1035 // At the start of the line, +/- specific ObjectiveC method
1036 // declarations.
1037 if (Tok->Parent == NULL)
1038 Tok->Type = TT_ObjCMethodSpecifier;
1039 break;
Nico Weberbcfdd262013-01-12 06:18:40 +00001040 case tok::colon:
1041 // Colons from ?: are handled in parseConditional().
Daniel Jasper1f2b0782013-01-16 16:23:19 +00001042 if (Tok->Parent->is(tok::r_paren))
1043 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper3b9a8fc2013-01-28 13:21:16 +00001044 else if (ColonIsObjCMethodExpr)
Nico Weberbcfdd262013-01-12 06:18:40 +00001045 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper3b9a8fc2013-01-28 13:21:16 +00001046 else if (ColonIsForRangeExpr)
1047 Tok->Type = TT_RangeBasedForLoopColon;
Nico Weberbcfdd262013-01-12 06:18:40 +00001048 break;
Nico Weber5096a442013-01-17 17:17:19 +00001049 case tok::kw_if:
1050 case tok::kw_while:
Manuel Klimek092a2c72013-01-23 10:09:28 +00001051 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber5096a442013-01-17 17:17:19 +00001052 next();
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001053 if (!parseParens(/*LookForDecls=*/ true))
Nico Weber5096a442013-01-17 17:17:19 +00001054 return false;
1055 }
1056 break;
Daniel Jasper3b9a8fc2013-01-28 13:21:16 +00001057 case tok::kw_for:
1058 ColonIsForRangeExpr = true;
1059 next();
1060 if (!parseParens())
1061 return false;
1062 break;
Nico Weber94fb7292013-01-18 05:50:57 +00001063 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001064 if (!parseParens())
1065 return false;
Nico Weber94fb7292013-01-18 05:50:57 +00001066 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001067 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001068 if (!parseSquare())
1069 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001070 break;
Daniel Jasper700e7102013-01-10 09:26:47 +00001071 case tok::l_brace:
1072 if (!parseBrace())
1073 return false;
1074 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001075 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +00001076 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +00001077 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001078 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001079 Tok->Type = TT_BinaryOperator;
1080 CurrentToken = Tok;
1081 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001082 }
1083 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001084 case tok::r_paren:
1085 case tok::r_square:
1086 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +00001087 case tok::r_brace:
1088 // Lines can start with '}'.
1089 if (Tok->Parent != NULL)
1090 return false;
1091 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001092 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001093 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001094 break;
1095 case tok::kw_operator:
Manuel Klimek092a2c72013-01-23 10:09:28 +00001096 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001097 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001098 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001099 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1100 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001101 next();
1102 }
1103 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001104 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1105 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001106 next();
1107 }
1108 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001109 break;
1110 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +00001111 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001112 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001113 case tok::kw_template:
1114 parseTemplateDeclaration();
1115 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001116 default:
1117 break;
1118 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001119 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001120 }
1121
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001122 void parseIncludeDirective() {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001123 next();
1124 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1125 next();
1126 while (CurrentToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +00001127 if (CurrentToken->isNot(tok::comment) ||
1128 !CurrentToken->Children.empty())
1129 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001130 next();
1131 }
1132 } else {
1133 while (CurrentToken != NULL) {
1134 next();
1135 }
1136 }
1137 }
1138
1139 void parseWarningOrError() {
1140 next();
1141 // We still want to format the whitespace left of the first token of the
1142 // warning or error.
1143 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001144 while (CurrentToken != NULL) {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001145 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001146 next();
1147 }
1148 }
1149
1150 void parsePreprocessorDirective() {
1151 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001152 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001153 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001154 // Hashes in the middle of a line can lead to any strange token
1155 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001156 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001157 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001158 switch (
1159 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001160 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +00001161 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001162 parseIncludeDirective();
1163 break;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001164 case tok::pp_error:
1165 case tok::pp_warning:
1166 parseWarningOrError();
1167 break;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001168 default:
1169 break;
1170 }
1171 }
1172
Daniel Jasper71607512013-01-07 10:48:50 +00001173 LineType parseLine() {
Daniel Jasper32983272013-01-22 14:28:24 +00001174 int PeriodsAndArrows = 0;
Daniel Jasperae8699b2013-01-28 09:35:24 +00001175 bool CanBeBuilderTypeStmt = true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001176 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001177 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +00001178 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001179 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001180 while (CurrentToken != NULL) {
1181 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +00001182 KeywordVirtualFound = true;
Daniel Jasper32983272013-01-22 14:28:24 +00001183 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1184 ++PeriodsAndArrows;
Daniel Jasperae8699b2013-01-28 09:35:24 +00001185 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1186 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1187 CanBeBuilderTypeStmt = false;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001188 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +00001189 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001190 }
Daniel Jasper71607512013-01-07 10:48:50 +00001191 if (KeywordVirtualFound)
1192 return LT_VirtualFunctionDecl;
Daniel Jasper32983272013-01-22 14:28:24 +00001193
1194 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasperae8699b2013-01-28 09:35:24 +00001195 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper32983272013-01-22 14:28:24 +00001196 return LT_BuilderTypeCall;
1197
Daniel Jasper71607512013-01-07 10:48:50 +00001198 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001199 }
1200
1201 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001202 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1203 CurrentToken = &CurrentToken->Children[0];
1204 else
1205 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001206 }
1207
1208 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001209 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +00001210 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +00001211 bool ColonIsObjCMethodExpr;
Daniel Jasper3b9a8fc2013-01-28 13:21:16 +00001212 bool ColonIsForRangeExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001213 };
1214
Daniel Jasper26f7e782013-01-08 14:56:18 +00001215 void calculateExtraInformation(AnnotatedToken &Current) {
1216 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1217
Manuel Klimek526ed112013-01-09 15:25:02 +00001218 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001219 Current.MustBreakBefore = true;
1220 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +00001221 if (Current.Type == TT_LineComment) {
1222 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001223 } else if ((Current.Parent->is(tok::comment) &&
1224 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper487f64b2013-01-13 16:10:20 +00001225 (Current.is(tok::string_literal) &&
1226 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +00001227 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +00001228 } else {
1229 Current.MustBreakBefore = false;
1230 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001231 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001232 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001233 if (Current.MustBreakBefore)
1234 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1235 else
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001236 Current.TotalLength =
1237 Current.Parent->TotalLength + Current.FormatTok.TokenLength +
1238 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasperb3109e32013-01-29 15:15:59 +00001239 // FIXME: Only calculate this if CanBreakBefore is true once static
1240 // initializers etc. are sorted out.
1241 Current.SplitPenalty = splitPenalty(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001242 if (!Current.Children.empty())
1243 calculateExtraInformation(Current.Children[0]);
1244 }
1245
Daniel Jasper995e8202013-01-14 13:08:07 +00001246 void annotate() {
Daniel Jasper995e8202013-01-14 13:08:07 +00001247 AnnotatingParser Parser(Line.First);
1248 Line.Type = Parser.parseLine();
1249 if (Line.Type == LT_Invalid)
1250 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001251
Daniel Jasper83f25ba2013-01-28 15:16:31 +00001252 bool LookForFunctionName = Line.MustBeDeclaration;
1253 determineTokenTypes(Line.First, /*IsExpression=*/ false,
1254 LookForFunctionName);
Daniel Jasper71607512013-01-07 10:48:50 +00001255
Daniel Jasper995e8202013-01-14 13:08:07 +00001256 if (Line.First.Type == TT_ObjCMethodSpecifier)
1257 Line.Type = LT_ObjCMethodDecl;
1258 else if (Line.First.Type == TT_ObjCDecl)
1259 Line.Type = LT_ObjCDecl;
1260 else if (Line.First.Type == TT_ObjCProperty)
1261 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +00001262
Daniel Jasper995e8202013-01-14 13:08:07 +00001263 Line.First.SpaceRequiredBefore = true;
1264 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1265 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001266
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001267 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper995e8202013-01-14 13:08:07 +00001268 if (!Line.First.Children.empty())
1269 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001270 }
1271
1272private:
Daniel Jasperadc6aba2013-01-29 15:03:01 +00001273 /// \brief Calculate the penalty for splitting before \c Tok.
1274 unsigned splitPenalty(const AnnotatedToken &Tok) {
1275 const AnnotatedToken &Left = *Tok.Parent;
1276 const AnnotatedToken &Right = Tok;
1277
1278 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
1279 return 50;
1280 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1281 return 150;
1282 if (Left.is(tok::coloncolon))
1283 return 500;
1284
1285 if (Left.Type == TT_RangeBasedForLoopColon)
1286 return 5;
1287
1288 if (Right.is(tok::arrow) || Right.is(tok::period)) {
1289 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
1290 return 5; // Should be smaller than breaking at a nested comma.
1291 return 150;
1292 }
1293
1294 // In for-loops, prefer breaking at ',' and ';'.
1295 if (Line.First.is(tok::kw_for) &&
1296 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
1297 return 20;
1298
1299 if (Left.is(tok::semi) || Left.is(tok::comma))
1300 return 0;
1301
1302 // In Objective-C method expressions, prefer breaking before "param:" over
1303 // breaking after it.
1304 if (isObjCSelectorName(Right))
1305 return 0;
1306 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1307 return 20;
1308
1309 if (Left.is(tok::l_paren))
1310 return 20;
1311 // FIXME: The penalty for a trailing "<" or "[" being higher than the
1312 // penalty for a trainling "(" is a temporary workaround until we can
1313 // properly avoid breaking in array subscripts or template parameters.
1314 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
1315 return 50;
1316
1317 if (Left.Type == TT_ConditionalExpr)
1318 return prec::Assignment;
1319 prec::Level Level = getPrecedence(Left);
1320
1321 if (Level != prec::Unknown)
1322 return Level;
1323
1324 return 3;
1325 }
1326
Daniel Jasper83f25ba2013-01-28 15:16:31 +00001327 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression,
1328 bool LookForFunctionName) {
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001329 if (getPrecedence(Current) == prec::Assignment) {
1330 IsExpression = true;
1331 AnnotatedToken *Previous = Current.Parent;
1332 while (Previous != NULL) {
Manuel Klimeka32a7fd2013-01-23 14:08:21 +00001333 if (Previous->Type == TT_BinaryOperator &&
1334 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001335 Previous->Type = TT_PointerOrReference;
Manuel Klimeka32a7fd2013-01-23 14:08:21 +00001336 }
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001337 Previous = Previous->Parent;
1338 }
1339 }
1340 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper20d35832013-01-23 12:58:14 +00001341 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1342 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001343 IsExpression = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001344
Daniel Jasper26f7e782013-01-08 14:56:18 +00001345 if (Current.Type == TT_Unknown) {
Daniel Jasper83f25ba2013-01-28 15:16:31 +00001346 if (LookForFunctionName && Current.is(tok::l_paren)) {
1347 findFunctionName(&Current);
1348 LookForFunctionName = false;
1349 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001350 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasper886568d2013-01-09 08:36:49 +00001351 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1352 Current.is(tok::caret)) {
1353 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001354 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1355 Current.Type = determineIncrementUsage(Current);
1356 } else if (Current.is(tok::exclaim)) {
1357 Current.Type = TT_UnaryOperator;
1358 } else if (isBinaryOperator(Current)) {
1359 Current.Type = TT_BinaryOperator;
1360 } else if (Current.is(tok::comment)) {
1361 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1362 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +00001363 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001364 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001365 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001366 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001367 } else if (Current.is(tok::r_paren) &&
1368 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001369 Current.Parent->Type == TT_TemplateCloser) &&
1370 (Current.Children.empty() ||
1371 (Current.Children[0].isNot(tok::equal) &&
1372 Current.Children[0].isNot(tok::semi) &&
1373 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001374 // FIXME: We need to get smarter and understand more cases of casts.
1375 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001376 } else if (Current.is(tok::at) && Current.Children.size()) {
1377 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1378 case tok::objc_interface:
1379 case tok::objc_implementation:
1380 case tok::objc_protocol:
1381 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001382 break;
1383 case tok::objc_property:
1384 Current.Type = TT_ObjCProperty;
1385 break;
Nico Webered91bba2013-01-10 19:19:14 +00001386 default:
1387 break;
1388 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001389 }
1390 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001391
1392 if (!Current.Children.empty())
Daniel Jasper83f25ba2013-01-28 15:16:31 +00001393 determineTokenTypes(Current.Children[0], IsExpression,
1394 LookForFunctionName);
1395 }
1396
1397 /// \brief Starting from \p Current, this searches backwards for an
1398 /// identifier which could be the start of a function name and marks it.
1399 void findFunctionName(AnnotatedToken *Current) {
1400 AnnotatedToken *Parent = Current->Parent;
1401 while (Parent != NULL && Parent->Parent != NULL) {
1402 if (Parent->is(tok::identifier) &&
1403 (Parent->Parent->is(tok::identifier) ||
1404 Parent->Parent->Type == TT_PointerOrReference ||
1405 Parent->Parent->Type == TT_TemplateCloser)) {
1406 Parent->Type = TT_StartOfName;
1407 break;
1408 }
1409 Parent = Parent->Parent;
1410 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001411 }
1412
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001413 /// \brief Returns the previous token ignoring comments.
1414 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1415 const AnnotatedToken *PrevToken = Tok.Parent;
1416 while (PrevToken != NULL && PrevToken->is(tok::comment))
1417 PrevToken = PrevToken->Parent;
1418 return PrevToken;
1419 }
1420
1421 /// \brief Returns the next token ignoring comments.
1422 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1423 if (Tok.Children.empty())
1424 return NULL;
1425 const AnnotatedToken *NextToken = &Tok.Children[0];
1426 while (NextToken->is(tok::comment)) {
1427 if (NextToken->Children.empty())
1428 return NULL;
1429 NextToken = &NextToken->Children[0];
1430 }
1431 return NextToken;
1432 }
1433
1434 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001435 TokenType
1436 determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001437 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1438 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001439 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001440
1441 const AnnotatedToken *NextToken = getNextToken(Tok);
1442 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001443 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001444
Daniel Jasperffee1712013-01-22 11:46:26 +00001445 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1446 return TT_PointerOrReference;
1447
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001448 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1449 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1450 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1451 PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper48bd7b72013-01-16 16:04:06 +00001452 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001453 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001454
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001455 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1456 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1457 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1458 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1459 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1460 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1461 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001462 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001463
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001464 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1465 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001466 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001467
Daniel Jasper112fb272012-12-05 07:51:39 +00001468 // It is very unlikely that we are going to find a pointer or reference type
1469 // definition on the RHS of an assignment.
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001470 if (IsExpression)
Daniel Jasper71607512013-01-07 10:48:50 +00001471 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001472
Daniel Jasper71607512013-01-07 10:48:50 +00001473 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001474 }
1475
Daniel Jasper886568d2013-01-09 08:36:49 +00001476 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001477 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1478 if (PrevToken == NULL)
1479 return TT_UnaryOperator;
1480
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001481 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001482 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1483 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1484 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1485 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1486 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001487 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001488
1489 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001490 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001491 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001492
1493 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001494 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001495 }
1496
1497 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001498 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001499 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1500 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001501 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001502 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1503 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001504 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001505
Daniel Jasper71607512013-01-07 10:48:50 +00001506 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001507 }
1508
Daniel Jasper26f7e782013-01-08 14:56:18 +00001509 bool spaceRequiredBetween(const AnnotatedToken &Left,
1510 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001511 if (Right.is(tok::hashhash))
1512 return Left.is(tok::hash);
1513 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1514 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001515 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1516 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001517 if (Right.is(tok::less) &&
1518 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001519 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001520 return true;
1521 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1522 return false;
1523 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1524 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001525 if (Left.is(tok::at) &&
1526 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1527 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001528 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1529 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001530 return false;
Daniel Jasper6b825c22013-01-16 07:19:28 +00001531 if (Left.is(tok::coloncolon))
1532 return false;
1533 if (Right.is(tok::coloncolon))
1534 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001535 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1536 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001537 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001538 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001539 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1540 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001541 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001542 return Right.FormatTok.Tok.isLiteral() ||
1543 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001544 if (Right.is(tok::star) && Left.is(tok::l_paren))
1545 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001546 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1547 return false;
1548 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001549 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001550 if (Left.is(tok::period) || Right.is(tok::period))
1551 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001552 if (Left.is(tok::colon))
1553 return Left.Type != TT_ObjCMethodExpr;
1554 if (Right.is(tok::colon))
1555 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001556 if (Left.is(tok::l_paren))
1557 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001558 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001559 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001560 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001561 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001562 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1563 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001564 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001565 if (Left.is(tok::at) &&
1566 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001567 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001568 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1569 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001570 return true;
1571 }
1572
Daniel Jasper26f7e782013-01-08 14:56:18 +00001573 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001574 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001575 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1576 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001577 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001578 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001579 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001580 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weberaab60052013-01-17 06:14:50 +00001581 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001582 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001583 // Don't space between ')' and <id>
1584 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001585 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001586 // Don't space between ':' and '('
1587 return false;
1588 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001589 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001590 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1591 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001592
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001593 if (Tok.Parent->is(tok::comma))
1594 return true;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001595 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001596 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001597 if (Tok.Type == TT_OverloadedOperator)
1598 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001599 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001600 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001601 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001602 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001603 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001604 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001605 if (Tok.Parent->Type == TT_UnaryOperator ||
1606 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001607 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001608 if (Tok.Type == TT_UnaryOperator)
1609 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001610 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1611 (Tok.Parent->isNot(tok::colon) ||
1612 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001613 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1614 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001615 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1616 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001617 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001618 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001619 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001620 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001621 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001622 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001623 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001624 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001625 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001626 }
1627
Daniel Jasper26f7e782013-01-08 14:56:18 +00001628 bool canBreakBefore(const AnnotatedToken &Right) {
1629 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001630 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001631 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1632 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001633 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001634 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1635 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001636 // Don't break this identifier as ':' or identifier
1637 // before it will break.
1638 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001639 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1640 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001641 // Don't break at ':' if identifier before it can beak.
1642 return false;
1643 }
Daniel Jasperd75ff642013-01-28 15:40:20 +00001644 if (Right.Type == TT_StartOfName && Style.AllowReturnTypeOnItsOwnLine)
Daniel Jasper83f25ba2013-01-28 15:16:31 +00001645 return true;
Nico Weberbcfdd262013-01-12 06:18:40 +00001646 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1647 return false;
1648 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1649 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001650 if (isObjCSelectorName(Right))
1651 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001652 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001653 return true;
Daniel Jasperbfe6fd42013-01-28 12:45:14 +00001654 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1655 return true;
Daniel Jasper3b9a8fc2013-01-28 13:21:16 +00001656 if (Left.Type == TT_RangeBasedForLoopColon)
1657 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001658 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperbfe6fd42013-01-28 12:45:14 +00001659 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1660 Left.is(tok::question))
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001661 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001662 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001663 return false;
1664
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001665 if (Right.Type == TT_LineComment)
Daniel Jasper487f64b2013-01-13 16:10:20 +00001666 // We rely on MustBreakBefore being set correctly here as we should not
1667 // change the "binding" behavior of a comment.
1668 return false;
1669
Daniel Jasper60ca75d2013-01-17 13:31:52 +00001670 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1671 // unless it is follow by ';', '{' or '='.
1672 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1673 Left.Parent->is(tok::r_paren))
1674 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1675 Right.isNot(tok::equal);
1676
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001677 // We only break before r_brace if there was a corresponding break before
1678 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1679 if (Right.is(tok::r_brace))
1680 return false;
1681
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001682 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001683 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001684 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1685 Left.is(tok::comma) || Right.is(tok::lessless) ||
1686 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper63f00362013-01-25 10:57:27 +00001687 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1688 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper63f00362013-01-25 10:57:27 +00001689 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1690 Right.is(tok::identifier)) ||
Daniel Jasper986e17f2013-01-28 07:35:34 +00001691 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1692 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001693 }
1694
Daniel Jasperbac016b2012-12-03 18:12:45 +00001695 FormatStyle Style;
1696 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001697 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001698 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001699};
1700
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001701class LexerBasedFormatTokenSource : public FormatTokenSource {
1702public:
1703 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001704 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001705 IdentTable(Lex.getLangOpts()) {
1706 Lex.SetKeepWhitespaceMode(true);
1707 }
1708
1709 virtual FormatToken getNextToken() {
1710 if (GreaterStashed) {
1711 FormatTok.NewlinesBefore = 0;
1712 FormatTok.WhiteSpaceStart =
1713 FormatTok.Tok.getLocation().getLocWithOffset(1);
1714 FormatTok.WhiteSpaceLength = 0;
1715 GreaterStashed = false;
1716 return FormatTok;
1717 }
1718
1719 FormatTok = FormatToken();
1720 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001721 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001722 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001723 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1724 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001725
1726 // Consume and record whitespace until we find a significant token.
1727 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001728 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001729 FormatTok.HasUnescapedNewline =
1730 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001731 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1732
1733 if (FormatTok.Tok.is(tok::eof))
1734 return FormatTok;
1735 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001736 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001737 }
Manuel Klimek95419382013-01-07 07:56:50 +00001738
1739 // Now FormatTok is the next non-whitespace token.
1740 FormatTok.TokenLength = Text.size();
1741
Manuel Klimekd4397b92013-01-04 23:34:14 +00001742 // In case the token starts with escaped newlines, we want to
1743 // take them into account as whitespace - this pattern is quite frequent
1744 // in macro definitions.
1745 // FIXME: What do we want to do with other escaped spaces, and escaped
1746 // spaces or newlines in the middle of tokens?
1747 // FIXME: Add a more explicit test.
1748 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001749 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001750 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001751 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001752 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001753 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001754 }
1755
1756 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001757 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001758 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001759 FormatTok.Tok.setKind(Info.getTokenID());
1760 }
1761
1762 if (FormatTok.Tok.is(tok::greatergreater)) {
1763 FormatTok.Tok.setKind(tok::greater);
1764 GreaterStashed = true;
1765 }
1766
1767 return FormatTok;
1768 }
1769
1770private:
1771 FormatToken FormatTok;
1772 bool GreaterStashed;
1773 Lexer &Lex;
1774 SourceManager &SourceMgr;
1775 IdentifierTable IdentTable;
1776
1777 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001778 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001779 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1780 Tok.getLength());
1781 }
1782};
1783
Daniel Jasperbac016b2012-12-03 18:12:45 +00001784class Formatter : public UnwrappedLineConsumer {
1785public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001786 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1787 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001788 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001789 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001790 Whitespaces(SourceMgr), Ranges(Ranges) {
1791 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001792
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001793 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001794
Daniel Jasperbac016b2012-12-03 18:12:45 +00001795 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001796 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001797 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001798 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001799 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001800 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1801 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1802 Annotator.annotate();
1803 }
1804 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1805 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001806 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001807 const AnnotatedLine &TheLine = *I;
1808 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001809 unsigned Indent =
1810 formatFirstToken(TheLine.First, TheLine.Level,
1811 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001812 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001813 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001814 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001815 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001816 PreviousEndOfLineColumn = Formatter.format();
1817 } else {
1818 // If we did not reformat this unwrapped line, the column at the end of
1819 // the last token is unchanged - thus, we can calculate the end of the
1820 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001821 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001822 SourceMgr.getSpellingColumnNumber(
1823 TheLine.Last->FormatTok.Tok.getLocation()) +
1824 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001825 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001826 }
1827 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001828 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001829 }
1830
1831private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001832 /// \brief Tries to merge lines into one.
1833 ///
1834 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1835 /// if possible; note that \c I will be incremented when lines are merged.
1836 ///
1837 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001838 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001839 std::vector<AnnotatedLine>::iterator &I,
1840 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001841 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1842
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001843 // We can never merge stuff if there are trailing line comments.
1844 if (I->Last->Type == TT_LineComment)
1845 return;
1846
Manuel Klimek517e8942013-01-11 17:54:10 +00001847 // Check whether the UnwrappedLine can be put onto a single line. If
1848 // so, this is bound to be the optimal solution (by definition) and we
1849 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001850 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001851 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001852 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001853
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001854 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001855 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001856
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001857 if (I->Last->is(tok::l_brace)) {
1858 tryMergeSimpleBlock(I, E, Limit);
1859 } else if (I->First.is(tok::kw_if)) {
1860 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001861 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1862 I->First.FormatTok.IsFirst)) {
1863 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001864 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001865 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001866 }
1867
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001868 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1869 std::vector<AnnotatedLine>::iterator E,
1870 unsigned Limit) {
1871 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001872 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1873 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001874 if (I + 2 != E && (I + 2)->InPPDirective &&
1875 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1876 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001877 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001878 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001879 join(Line, *(++I));
1880 }
1881
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001882 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1883 std::vector<AnnotatedLine>::iterator E,
1884 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001885 if (!Style.AllowShortIfStatementsOnASingleLine)
1886 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001887 if ((I + 1)->InPPDirective != I->InPPDirective ||
1888 ((I + 1)->InPPDirective &&
1889 (I + 1)->First.FormatTok.HasUnescapedNewline))
1890 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001891 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001892 if (Line.Last->isNot(tok::r_paren))
1893 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001894 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001895 return;
1896 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1897 return;
1898 // Only inline simple if's (no nested if or else).
1899 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1900 return;
1901 join(Line, *(++I));
1902 }
1903
1904 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001905 std::vector<AnnotatedLine>::iterator E,
1906 unsigned Limit) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001907 // First, check that the current line allows merging. This is the case if
1908 // we're not in a control flow statement and the last token is an opening
1909 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001910 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001911 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001912 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1913 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1914 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1915 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001916 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001917 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1918 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001919 if (!AllowedTokens)
1920 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001921
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001922 AnnotatedToken *Tok = &(I + 1)->First;
1923 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1924 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1925 Tok->SpaceRequiredBefore = false;
1926 join(Line, *(I + 1));
1927 I += 1;
1928 } else {
1929 // Check that we still have three lines and they fit into the limit.
1930 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1931 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001932 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001933
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001934 // Second, check that the next line does not contain any braces - if it
1935 // does, readability declines when putting it into a single line.
1936 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1937 return;
1938 do {
1939 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1940 return;
1941 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1942 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001943
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001944 // Last, check that the third line contains a single closing brace.
1945 Tok = &(I + 2)->First;
1946 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1947 Tok->MustBreakBefore)
1948 return;
1949
1950 join(Line, *(I + 1));
1951 join(Line, *(I + 2));
1952 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001953 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001954 }
1955
1956 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1957 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001958 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1959 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001960 }
1961
Daniel Jasper995e8202013-01-14 13:08:07 +00001962 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1963 A.Last->Children.push_back(B.First);
1964 while (!A.Last->Children.empty()) {
1965 A.Last->Children[0].Parent = A.Last;
1966 A.Last = &A.Last->Children[0];
1967 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001968 }
1969
Daniel Jasper995e8202013-01-14 13:08:07 +00001970 bool touchesRanges(const AnnotatedLine &TheLine) {
1971 const FormatToken *First = &TheLine.First.FormatTok;
1972 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001973 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001974 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001975 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001976 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1977 Ranges[i].getBegin()) &&
1978 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1979 LineRange.getBegin()))
1980 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001981 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001982 return false;
1983 }
1984
1985 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001986 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001987 }
1988
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001989 /// \brief Add a new line and the required indent before the first Token
1990 /// of the \c UnwrappedLine if there was no structural parsing error.
1991 /// Returns the indent level of the \c UnwrappedLine.
1992 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1993 bool InPPDirective,
1994 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001995 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001996 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1997 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1998
Daniel Jasper1a1ce832013-01-29 11:27:30 +00001999 unsigned Newlines =
2000 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00002001 if (Newlines == 0 && !Tok.IsFirst)
2002 Newlines = 1;
2003 unsigned Indent = Level * 2;
2004
2005 bool IsAccessModifier = false;
2006 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
2007 RootToken.is(tok::kw_private))
2008 IsAccessModifier = true;
2009 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
2010 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
2011 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
2012 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
2013 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
2014 IsAccessModifier = true;
2015
2016 if (IsAccessModifier &&
2017 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
2018 Indent += Style.AccessModifierOffset;
2019 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00002020 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00002021 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00002022 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
2023 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00002024 }
2025 return Indent;
2026 }
2027
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00002028 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00002029 FormatStyle Style;
2030 Lexer &Lex;
2031 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00002032 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00002033 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00002034 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00002035 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00002036};
2037
Daniel Jasper1a1ce832013-01-29 11:27:30 +00002038tooling::Replacements
2039reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
2040 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00002041 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00002042 OwningPtr<DiagnosticConsumer> DiagPrinter;
2043 if (DiagClient == 0) {
2044 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
2045 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
2046 DiagClient = DiagPrinter.get();
2047 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00002048 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002049 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00002050 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00002051 Diagnostics.setSourceManager(&SourceMgr);
2052 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00002053 return formatter.format();
2054}
2055
Daniel Jasper46ef8522013-01-10 13:08:12 +00002056LangOptions getFormattingLangOpts() {
2057 LangOptions LangOpts;
2058 LangOpts.CPlusPlus = 1;
2059 LangOpts.CPlusPlus11 = 1;
2060 LangOpts.Bool = 1;
2061 LangOpts.ObjC1 = 1;
2062 LangOpts.ObjC2 = 1;
2063 return LangOpts;
2064}
2065
Daniel Jaspercd162382013-01-07 13:26:07 +00002066} // namespace format
2067} // namespace clang