blob: ecd6f5d3854bf3d9ec63094ae4e5a01ab12a14bb [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasperd2639ef2013-01-28 15:16:31 +000053 TT_RangeBasedForLoopColon,
54 TT_StartOfName,
Daniel Jasper7194e182013-01-10 11:14:08 +000055 TT_TemplateCloser,
56 TT_TemplateOpener,
57 TT_TrailingUnaryOperator,
58 TT_UnaryOperator,
59 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000060};
61
62enum LineType {
63 LT_Invalid,
64 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000065 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000066 LT_PreprocessorDirective,
67 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000068 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000069 LT_ObjCMethodDecl,
70 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000071};
72
Daniel Jasper7c85fde2013-01-08 14:56:18 +000073class AnnotatedToken {
74public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000075 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000076 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
77 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000078 ClosesTemplateDeclaration(false), MatchingParen(NULL),
79 ParameterCount(1), Parent(NULL) {
80 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000081
Daniel Jasper25837aa2013-01-14 14:14:23 +000082 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
83 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
84
Daniel Jasper7c85fde2013-01-08 14:56:18 +000085 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
86 return FormatTok.Tok.isObjCAtKeyword(Kind);
87 }
88
89 FormatToken FormatTok;
90
Daniel Jasperf7935112012-12-03 18:12:45 +000091 TokenType Type;
92
Daniel Jasperf7935112012-12-03 18:12:45 +000093 bool SpaceRequiredBefore;
94 bool CanBreakBefore;
95 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000096
97 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000098
Daniel Jasper9278eb92013-01-16 14:59:02 +000099 AnnotatedToken *MatchingParen;
100
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000101 /// \brief Number of parameters, if this is "(", "[" or "<".
102 ///
103 /// This is initialized to 1 as we don't need to distinguish functions with
104 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
105 /// the number of commas.
106 unsigned ParameterCount;
107
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000108 /// \brief The total length of the line up to and including this token.
109 unsigned TotalLength;
110
Daniel Jaspercf330002013-01-29 15:03:01 +0000111 /// \brief Penalty for inserting a line break before this token.
112 unsigned SplitPenalty;
113
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000114 std::vector<AnnotatedToken> Children;
115 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-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 Jasperf7935112012-12-03 18:12:45 +0000123};
124
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000125class AnnotatedLine {
126public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000127 AnnotatedLine(const UnwrappedLine &Line)
128 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000129 InPPDirective(Line.InPPDirective),
130 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-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 Jasperaa701fa2013-01-18 08:44:07 +0000136 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-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 Klimek0a3a3c92013-01-23 09:32:48 +0000144 InPPDirective(Other.InPPDirective),
145 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-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 Jasperf1e4b7d2013-01-14 13:08:07 +0000153 AnnotatedToken First;
154 AnnotatedToken *Last;
155
156 LineType Type;
157 unsigned Level;
158 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000159 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000160};
161
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000162static prec::Level getPrecedence(const AnnotatedToken &Tok) {
163 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000164}
165
Daniel Jasper20b09ef2013-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 Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +0000178 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000179 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000180 LLVMStyle.BinPackParameters = true;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000181 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +0000182 LLVMStyle.AllowReturnTypeOnItsOwnLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000183 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000184 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000185 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-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 Kornienko578fdd82012-12-06 18:03:27 +0000196 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000197 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000198 GoogleStyle.BinPackParameters = false;
Daniel Jasperf7db4332013-01-29 16:03:49 +0000199 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
Daniel Jasperd36ef5e2013-01-28 15:40:20 +0000200 GoogleStyle.AllowReturnTypeOnItsOwnLine = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000201 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000202 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000203 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000204 return GoogleStyle;
205}
206
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000207FormatStyle getChromiumStyle() {
208 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasperf7db4332013-01-29 16:03:49 +0000209 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
Daniel Jasper17fdaa42013-01-29 15:19:38 +0000210 ChromiumStyle.SplitTemplateClosingGreater = true;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000211 return ChromiumStyle;
212}
213
Daniel Jasperf7935112012-12-03 18:12:45 +0000214struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000215 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +0000216 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000217};
218
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000219/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000220///
Daniel Jasperaa701fa2013-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 Jasper304a9862013-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 Jasperaa701fa2013-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 Jasperbbc84152013-01-29 11:27:30 +0000247 Comments.back().MaxColumn =
248 Style.ColumnLimit - Spaces - Tok.FormatTok.TokenLength;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000249 return;
250 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000251 }
Daniel Jasper304a9862013-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 Jasperaa701fa2013-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 Jasperbbc84152013-01-29 11:27:30 +0000270 unsigned Offset =
271 std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
Daniel Jasperaa701fa2013-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 Klimek0b689fd2013-01-10 18:45:26 +0000327 }
328 }
Daniel Jasperaa701fa2013-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 Klimek0b689fd2013-01-10 18:45:26 +0000340
Nico Weberc9d73612013-01-12 22:48:47 +0000341/// \brief Returns if a token is an Objective-C selector name.
342///
Nico Weber92c05392013-01-12 22:51:13 +0000343/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-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 Jasperf7935112012-12-03 18:12:45 +0000350class UnwrappedLineFormatter {
351public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000352 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000353 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000354 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000355 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000356 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000357 FirstIndent(FirstIndent), RootToken(RootToken),
358 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000359 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000360 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000361 }
362
Manuel Klimek1abf7892013-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 Jaspere9de2602012-12-06 09:56:08 +0000368 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000369 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000370 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000371 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000372 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000373 State.VariablePos = 0;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000374 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000375
Manuel Klimek24998102013-01-16 14:55:28 +0000376 DEBUG({
377 DebugTokenState(*State.NextToken);
378 });
379
Daniel Jaspere9de2602012-12-06 09:56:08 +0000380 // The first token has already been indented and thus consumed.
381 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000382
383 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000384 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-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 Jasperbbc84152013-01-29 11:27:30 +0000391 State.NextToken = State.NextToken->Children.empty()
392 ? NULL : &State.NextToken->Children[0];
Daniel Jasper997b08c2013-01-18 09:19:33 +0000393 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-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 Klimek24998102013-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 Jasper2af6bbe2012-12-18 21:05:13 +0000410 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000411 if (State.NextToken != NULL &&
412 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
413 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000414 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000415 State.Stack.back().BreakAfterComma = true;
416 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000417 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000418 }
Manuel Klimek24998102013-01-16 14:55:28 +0000419 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000420 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000421 }
422
423private:
Manuel Klimek24998102013-01-16 14:55:28 +0000424 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
425 const Token &Tok = AnnotatedTok.FormatTok.Tok;
Daniel Jasperbbc84152013-01-29 11:27:30 +0000426 llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
427 Tok.getLength());
Manuel Klimek24998102013-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 Jasper337816e2013-01-11 10:22:12 +0000440 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000441 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000442 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000443 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000444 BreakAfterComma(false), HasMultiParameterLine(false) {
445 }
Daniel Jasper6d822722012-12-24 16:43:00 +0000446
Daniel Jasperf7935112012-12-03 18:12:45 +0000447 /// \brief The position to which a specific parenthesis level needs to be
448 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000450
Daniel Jaspere9de2602012-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 Jasper337816e2013-01-11 10:22:12 +0000456 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000457
Daniel Jaspera836b902013-01-23 16:58:21 +0000458 /// \brief This is the column of the first token after an assignment.
459 unsigned AssignmentColumn;
460
Daniel Jaspere9de2602012-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 Jasper337816e2013-01-11 10:22:12 +0000465 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000466
Manuel Klimek0ddd57a2013-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 Jasper337816e2013-01-11 10:22:12 +0000472 bool BreakBeforeClosingBrace;
473
Daniel Jasperca6623b2013-01-28 12:45:14 +0000474 /// \brief The column of a \c ? in a conditional expression;
475 unsigned QuestionColumn;
476
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000477 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000478 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000479
Daniel Jasper337816e2013-01-11 10:22:12 +0000480 bool operator<(const ParenState &Other) const {
481 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000482 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000483 if (LastSpace != Other.LastSpace)
484 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000485 if (AssignmentColumn != Other.AssignmentColumn)
486 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000487 if (FirstLessLess != Other.FirstLessLess)
488 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000489 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
490 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000491 if (QuestionColumn != Other.QuestionColumn)
492 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000493 if (BreakAfterComma != Other.BreakAfterComma)
494 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000495 if (HasMultiParameterLine != Other.HasMultiParameterLine)
496 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000497 return false;
Daniel Jasper337816e2013-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 Jasperbbc84152013-01-29 11:27:30 +0000511 /// \brief The column of the first variable name in a variable declaration.
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000512 ///
Daniel Jasperbbc84152013-01-29 11:27:30 +0000513 /// Used to align further variables if necessary.
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000514 unsigned VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000515
516 /// \brief \c true if this line contains a continued for-loop section.
517 bool LineContainsContinuedForLoopSection;
518
Daniel Jasper337816e2013-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 Jasper7c85fde2013-01-08 14:56:18 +0000525 if (Other.NextToken != NextToken)
526 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 if (Other.Column != Column)
528 return Other.Column > Column;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000529 if (Other.VariablePos != VariablePos)
530 return Other.VariablePos < VariablePos;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000531 if (Other.LineContainsContinuedForLoopSection !=
532 LineContainsContinuedForLoopSection)
533 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000534 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000535 }
536 };
537
Daniel Jasper6021c4a2012-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 Jasper337816e2013-01-11 10:22:12 +0000546 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000547 const AnnotatedToken &Current = *State.NextToken;
548 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000549 assert(State.Stack.size());
550 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000551
552 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000553 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000554 if (Current.is(tok::r_brace)) {
555 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-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 Jasper337816e2013-01-11 10:22:12 +0000560 State.Stack[ParenLevel].FirstLessLess != 0) {
561 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000562 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000563 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000564 Current.is(tok::period) || Current.is(tok::arrow) ||
565 Current.is(tok::question))) {
Daniel Jasper399d24b2013-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 Jasperca6623b2013-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 Jasper38c11ce2013-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 Jasperd2639ef2013-01-28 15:16:31 +0000577 } else if (State.NextToken->Parent->ClosesTemplateDeclaration ||
578 Current.Type == TT_StartOfName) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000579 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-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 Jasperfbde69e2012-12-21 14:37:20 +0000583 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000584 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000585 }
586
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000587 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000588 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000590 if (!DryRun) {
591 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000592 Whitespaces.replaceWhitespace(Current, 1, State.Column,
593 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000594 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000595 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
596 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000597 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000598
Daniel Jasper337816e2013-01-11 10:22:12 +0000599 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000600 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000602 } else {
Daniel Jasper38c11ce2013-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 Jasperfbde69e2012-12-21 14:37:20 +0000606
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000607 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
608 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000609 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000610
Daniel Jasperf7935112012-12-03 18:12:45 +0000611 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000612 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613
Daniel Jasperbcab4302013-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 Jasper206df732013-01-07 13:08:40 +0000617 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000618 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000619 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000620 if (Current.Type != TT_LineComment &&
621 (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
622 State.NextToken->Parent->Type == TT_TemplateOpener))
Daniel Jasper337816e2013-01-11 10:22:12 +0000623 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000624 if (Previous.is(tok::comma) && Current.Type != TT_LineComment)
Daniel Jasper9278eb92013-01-16 14:59:02 +0000625 State.Stack[ParenLevel].HasMultiParameterLine = true;
626
Daniel Jaspere9de2602012-12-06 09:56:08 +0000627 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000628 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
629 // Treat the condition inside an if as if it was a second function
630 // parameter, i.e. let nested calls have an indent of 4.
631 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000632 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000633 // Top-level spaces are exempt as that mostly leads to better results.
634 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000635 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000636 Previous.Type == TT_ConditionalExpr ||
637 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000638 getPrecedence(Previous) != prec::Assignment)
639 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000640 else if (Previous.ParameterCount > 1 &&
641 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
642 Previous.Type == TT_TemplateOpener))
643 // If this function has multiple parameters, indent nested calls from
644 // the start of the first parameter.
645 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000646 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000647
648 // If we break after an {, we should also break before the corresponding }.
649 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000650 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000651
Daniel Jaspere941b162013-01-23 10:08:28 +0000652 if (!Style.BinPackParameters && Newline) {
653 // If we are breaking after '(', '{', '<', this is not bin packing unless
Daniel Jasperf7db4332013-01-29 16:03:49 +0000654 // AllowAllParametersOfDeclarationOnNextLine is false.
Daniel Jaspere941b162013-01-23 10:08:28 +0000655 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
656 Previous.Type != TT_TemplateOpener) ||
Daniel Jasperf7db4332013-01-29 16:03:49 +0000657 (!Style.AllowAllParametersOfDeclarationOnNextLine &&
658 Line.MustBeDeclaration))
Daniel Jaspere941b162013-01-23 10:08:28 +0000659 State.Stack.back().BreakAfterComma = true;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000660
Daniel Jaspere941b162013-01-23 10:08:28 +0000661 // Any break on this level means that the parent level has been broken
662 // and we need to avoid bin packing there.
663 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
664 State.Stack[i].BreakAfterComma = true;
665 }
666 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000667
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000668 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000669 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000670
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000671 /// \brief Mark the next token as consumed in \p State and modify its stacks
672 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000673 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000674 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000675 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000676
Daniel Jasper337816e2013-01-11 10:22:12 +0000677 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
678 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000679 if (Current.is(tok::question))
680 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000681
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000682 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000683 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000684 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
685 Current.is(tok::l_brace) ||
686 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000687 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000688 if (Current.is(tok::l_brace)) {
689 // FIXME: This does not work with nested static initializers.
690 // Implement a better handling for static initializers and similar
691 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000692 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000693 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000694 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000695 }
Daniel Jasperbbc84152013-01-29 11:27:30 +0000696 State.Stack.push_back(ParenState(NewIndent,
697 State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000698 }
699
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000700 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000701 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000702 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
703 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
704 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000705 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000707
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000708 if (State.NextToken->Children.empty())
709 State.NextToken = NULL;
710 else
711 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000712
713 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000714 }
715
Daniel Jasper2df93312013-01-09 10:16:05 +0000716 unsigned getColumnLimit() {
717 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
718 }
719
Daniel Jasperf7935112012-12-03 18:12:45 +0000720 /// \brief Calculate the number of lines needed to format the remaining part
721 /// of the unwrapped line.
722 ///
723 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000724 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000725 /// added after the previous token.
726 ///
727 /// \param StopAt is used for optimization. If we can determine that we'll
728 /// definitely need at least \p StopAt additional lines, we already know of a
729 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000730 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000731 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000732 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 return 0;
734
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000735 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000736 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000737 if (NewLine && !State.NextToken->CanBreakBefore &&
738 !(State.NextToken->is(tok::r_brace) &&
739 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000741 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000742 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000743 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000744 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000745 State.LineContainsContinuedForLoopSection)
746 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000747 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasperddaa9be2013-01-29 19:41:55 +0000748 State.NextToken->Type != TT_LineComment &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000749 State.Stack.back().BreakAfterComma)
750 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000751 // Trying to insert a parameter on a new line if there are already more than
752 // one parameter on the current line is bin packing.
753 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
754 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
755 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000756 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
757 (State.NextToken->Parent->ClosesTemplateDeclaration &&
758 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000759 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000760
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000761 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000762 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000763 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jaspercf330002013-01-29 15:03:01 +0000764 State.NextToken->SplitPenalty;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000765
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000766 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000767
Daniel Jasper2df93312013-01-09 10:16:05 +0000768 // Exceeding column limit is bad, assign penalty.
769 if (State.Column > getColumnLimit()) {
770 unsigned ExcessCharacters = State.Column - getColumnLimit();
771 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
772 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000773
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 if (StopAt <= CurrentPenalty)
775 return UINT_MAX;
776 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000777 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000778 if (I != Memory.end()) {
779 // If this state has already been examined, we can safely return the
780 // previous result if we
781 // - have not hit the optimatization (and thus returned UINT_MAX) OR
782 // - are now computing for a smaller or equal StopAt.
783 unsigned SavedResult = I->second.first;
784 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000785 if (SavedResult != UINT_MAX)
786 return SavedResult + CurrentPenalty;
787 else if (StopAt <= SavedStopAt)
788 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000789 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000790
791 unsigned NoBreak = calcPenalty(State, false, StopAt);
792 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
793 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000794
795 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
796 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000797 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000798
799 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000800 }
801
Daniel Jasperf7935112012-12-03 18:12:45 +0000802 FormatStyle Style;
803 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000804 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000805 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000806 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000807 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000808
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000809 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000810 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000811 StateMap Memory;
812
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 OptimizationParameters Parameters;
814};
815
816/// \brief Determines extra information about the tokens comprising an
817/// \c UnwrappedLine.
818class TokenAnnotator {
819public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000820 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
821 AnnotatedLine &Line)
Daniel Jasperbbc84152013-01-29 11:27:30 +0000822 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {
823 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000824
825 /// \brief A parser that gathers additional information about tokens.
826 ///
827 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
828 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
829 /// into template parameter lists.
830 class AnnotatingParser {
831 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000832 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000833 : CurrentToken(&RootToken), KeywordVirtualFound(false),
Daniel Jasperbbc84152013-01-29 11:27:30 +0000834 ColonIsObjCMethodExpr(false), ColonIsForRangeExpr(false) {
835 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000836
Nico Weber250fe712013-01-18 02:43:57 +0000837 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
838 struct ObjCSelectorRAII {
839 AnnotatingParser &P;
840 bool ColonWasObjCMethodExpr;
841
842 ObjCSelectorRAII(AnnotatingParser &P)
Daniel Jasperbbc84152013-01-29 11:27:30 +0000843 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {
844 }
Nico Weber250fe712013-01-18 02:43:57 +0000845
846 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
847
848 void markStart(AnnotatedToken &Left) {
849 P.ColonIsObjCMethodExpr = true;
850 Left.Type = TT_ObjCMethodExpr;
851 }
852
853 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
854 };
855
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000856 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000857 if (CurrentToken == NULL)
858 return false;
859 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000860 while (CurrentToken != NULL) {
861 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000862 Left->MatchingParen = CurrentToken;
863 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000864 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000865 next();
866 return true;
867 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
869 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000870 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000871 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
872 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000873 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000874 if (CurrentToken->is(tok::comma))
875 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000876 if (!consumeToken())
877 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000878 }
879 return false;
880 }
881
Nico Weber80a82762013-01-17 17:17:19 +0000882 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000883 if (CurrentToken == NULL)
884 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000885 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000886 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000887 if (CurrentToken->is(tok::caret)) {
888 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000889 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000890 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
891 // @selector( starts a selector.
892 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
893 MaybeSel->Parent->is(tok::at)) {
894 StartsObjCMethodExpr = true;
895 }
896 }
897
898 ObjCSelectorRAII objCSelector(*this);
899 if (StartsObjCMethodExpr)
900 objCSelector.markStart(*Left);
901
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000902 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000903 // LookForDecls is set when "if (" has been seen. Check for
904 // 'identifier' '*' 'identifier' followed by not '=' -- this
905 // '*' has to be a binary operator but determineStarAmpUsage() will
906 // categorize it as an unary operator, so set the right type here.
907 if (LookForDecls && !CurrentToken->Children.empty()) {
908 AnnotatedToken &Prev = *CurrentToken->Parent;
909 AnnotatedToken &Next = CurrentToken->Children[0];
910 if (Prev.Parent->is(tok::identifier) &&
911 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
912 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
913 Prev.Type = TT_BinaryOperator;
914 LookForDecls = false;
915 }
916 }
917
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000918 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000919 Left->MatchingParen = CurrentToken;
920 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000921
922 if (StartsObjCMethodExpr)
923 objCSelector.markEnd(*CurrentToken);
924
Daniel Jasperf7935112012-12-03 18:12:45 +0000925 next();
926 return true;
927 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000928 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000930 if (CurrentToken->is(tok::comma))
931 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000932 if (!consumeToken())
933 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000934 }
935 return false;
936 }
937
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000938 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000939 if (!CurrentToken)
940 return false;
941
942 // A '[' could be an index subscript (after an indentifier or after
943 // ')' or ']'), or it could be the start of an Objective-C method
944 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000945 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000946 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000947 !Left->Parent || Left->Parent->is(tok::colon) ||
948 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
949 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
Daniel Jasperbbc84152013-01-29 11:27:30 +0000950 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(), true,
951 true) > prec::Unknown;
Nico Webera7252d82013-01-12 06:18:40 +0000952
Nico Weber250fe712013-01-18 02:43:57 +0000953 ObjCSelectorRAII objCSelector(*this);
954 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000955 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000956
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000957 while (CurrentToken != NULL) {
958 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000959 if (!CurrentToken->Children.empty() &&
960 CurrentToken->Children[0].is(tok::l_paren)) {
961 // An ObjC method call can't be followed by an open parenthesis.
962 // FIXME: Do we incorrectly label ":" with this?
963 StartsObjCMethodExpr = false;
964 Left->Type = TT_Unknown;
Daniel Jasper38c11ce2013-01-29 11:21:01 +0000965 }
Nico Weber250fe712013-01-18 02:43:57 +0000966 if (StartsObjCMethodExpr)
967 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000968 Left->MatchingParen = CurrentToken;
969 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000970 next();
971 return true;
972 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000973 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000974 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000975 if (CurrentToken->is(tok::comma))
976 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000977 if (!consumeToken())
978 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000979 }
980 return false;
981 }
982
Daniel Jasper83a54d22013-01-10 09:26:47 +0000983 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000984 // Lines are fine to end with '{'.
985 if (CurrentToken == NULL)
986 return true;
987 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000988 while (CurrentToken != NULL) {
989 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000990 Left->MatchingParen = CurrentToken;
991 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000992 next();
993 return true;
994 }
995 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
996 return false;
997 if (!consumeToken())
998 return false;
999 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001000 return true;
1001 }
1002
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001003 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001004 while (CurrentToken != NULL) {
1005 if (CurrentToken->is(tok::colon)) {
1006 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 next();
1008 return true;
1009 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001010 if (!consumeToken())
1011 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001012 }
1013 return false;
1014 }
1015
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001016 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001017 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1018 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001019 next();
1020 if (!parseAngle())
1021 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001022 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001023 return true;
1024 }
1025 return false;
1026 }
1027
Daniel Jasperc0880a92013-01-04 18:52:56 +00001028 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001029 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001032 case tok::plus:
1033 case tok::minus:
1034 // At the start of the line, +/- specific ObjectiveC method
1035 // declarations.
1036 if (Tok->Parent == NULL)
1037 Tok->Type = TT_ObjCMethodSpecifier;
1038 break;
Nico Webera7252d82013-01-12 06:18:40 +00001039 case tok::colon:
1040 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001041 if (Tok->Parent->is(tok::r_paren))
1042 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001043 else if (ColonIsObjCMethodExpr)
Nico Webera7252d82013-01-12 06:18:40 +00001044 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001045 else if (ColonIsForRangeExpr)
1046 Tok->Type = TT_RangeBasedForLoopColon;
Nico Webera7252d82013-01-12 06:18:40 +00001047 break;
Nico Weber80a82762013-01-17 17:17:19 +00001048 case tok::kw_if:
1049 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001050 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001051 next();
Daniel Jasperbbc84152013-01-29 11:27:30 +00001052 if (!parseParens(/*LookForDecls=*/ true))
Nico Weber80a82762013-01-17 17:17:19 +00001053 return false;
1054 }
1055 break;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001056 case tok::kw_for:
1057 ColonIsForRangeExpr = true;
1058 next();
1059 if (!parseParens())
1060 return false;
1061 break;
Nico Webera5510af2013-01-18 05:50:57 +00001062 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001063 if (!parseParens())
1064 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001065 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001067 if (!parseSquare())
1068 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001069 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001070 case tok::l_brace:
1071 if (!parseBrace())
1072 return false;
1073 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001074 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001075 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001076 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001077 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 Tok->Type = TT_BinaryOperator;
1079 CurrentToken = Tok;
1080 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001081 }
1082 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001083 case tok::r_paren:
1084 case tok::r_square:
1085 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001086 case tok::r_brace:
1087 // Lines can start with '}'.
1088 if (Tok->Parent != NULL)
1089 return false;
1090 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001091 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001092 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 break;
1094 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001095 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001096 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001097 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001098 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1099 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001100 next();
1101 }
1102 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001103 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1104 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001105 next();
1106 }
1107 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001108 break;
1109 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001110 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001111 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001112 case tok::kw_template:
1113 parseTemplateDeclaration();
1114 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001115 default:
1116 break;
1117 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001118 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001119 }
1120
Daniel Jasper050948a52012-12-21 17:58:39 +00001121 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001122 next();
1123 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1124 next();
1125 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001126 if (CurrentToken->isNot(tok::comment) ||
1127 !CurrentToken->Children.empty())
1128 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001129 next();
1130 }
1131 } else {
1132 while (CurrentToken != NULL) {
1133 next();
1134 }
1135 }
1136 }
1137
1138 void parseWarningOrError() {
1139 next();
1140 // We still want to format the whitespace left of the first token of the
1141 // warning or error.
1142 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001143 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001144 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001145 next();
1146 }
1147 }
1148
1149 void parsePreprocessorDirective() {
1150 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001152 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001153 // Hashes in the middle of a line can lead to any strange token
1154 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001155 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001156 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001157 switch (
1158 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001159 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001160 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001161 parseIncludeDirective();
1162 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001163 case tok::pp_error:
1164 case tok::pp_warning:
1165 parseWarningOrError();
1166 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001167 default:
1168 break;
1169 }
1170 }
1171
Daniel Jasperda16db32013-01-07 10:48:50 +00001172 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001173 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001174 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001175 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001176 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001177 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001178 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001179 while (CurrentToken != NULL) {
1180 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001181 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001182 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1183 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001184 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1185 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1186 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001187 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001188 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001189 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001190 if (KeywordVirtualFound)
1191 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001192
1193 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001194 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001195 return LT_BuilderTypeCall;
1196
Daniel Jasperda16db32013-01-07 10:48:50 +00001197 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001198 }
1199
1200 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001201 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1202 CurrentToken = &CurrentToken->Children[0];
1203 else
1204 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001205 }
1206
1207 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001208 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001209 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001210 bool ColonIsObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001211 bool ColonIsForRangeExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001212 };
1213
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001214 void calculateExtraInformation(AnnotatedToken &Current) {
1215 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1216
Manuel Klimek52b15152013-01-09 15:25:02 +00001217 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001218 Current.MustBreakBefore = true;
1219 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001220 if (Current.Type == TT_LineComment) {
1221 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001222 } else if ((Current.Parent->is(tok::comment) &&
1223 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001224 (Current.is(tok::string_literal) &&
1225 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001226 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001227 } else {
1228 Current.MustBreakBefore = false;
1229 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001230 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001231 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001232 if (Current.MustBreakBefore)
1233 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1234 else
Daniel Jasperbbc84152013-01-29 11:27:30 +00001235 Current.TotalLength =
1236 Current.Parent->TotalLength + Current.FormatTok.TokenLength +
1237 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper85f16f92013-01-29 15:15:59 +00001238 // FIXME: Only calculate this if CanBreakBefore is true once static
1239 // initializers etc. are sorted out.
1240 Current.SplitPenalty = splitPenalty(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001241 if (!Current.Children.empty())
1242 calculateExtraInformation(Current.Children[0]);
1243 }
1244
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001245 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001246 AnnotatingParser Parser(Line.First);
1247 Line.Type = Parser.parseLine();
1248 if (Line.Type == LT_Invalid)
1249 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001250
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001251 bool LookForFunctionName = Line.MustBeDeclaration;
1252 determineTokenTypes(Line.First, /*IsExpression=*/ false,
1253 LookForFunctionName);
Daniel Jasperda16db32013-01-07 10:48:50 +00001254
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001255 if (Line.First.Type == TT_ObjCMethodSpecifier)
1256 Line.Type = LT_ObjCMethodDecl;
1257 else if (Line.First.Type == TT_ObjCDecl)
1258 Line.Type = LT_ObjCDecl;
1259 else if (Line.First.Type == TT_ObjCProperty)
1260 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001261
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001262 Line.First.SpaceRequiredBefore = true;
1263 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1264 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001265
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001266 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 if (!Line.First.Children.empty())
1268 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001269 }
1270
1271private:
Daniel Jaspercf330002013-01-29 15:03:01 +00001272 /// \brief Calculate the penalty for splitting before \c Tok.
1273 unsigned splitPenalty(const AnnotatedToken &Tok) {
1274 const AnnotatedToken &Left = *Tok.Parent;
1275 const AnnotatedToken &Right = Tok;
1276
1277 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
1278 return 50;
1279 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1280 return 150;
1281 if (Left.is(tok::coloncolon))
1282 return 500;
1283
1284 if (Left.Type == TT_RangeBasedForLoopColon)
1285 return 5;
1286
1287 if (Right.is(tok::arrow) || Right.is(tok::period)) {
1288 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
1289 return 5; // Should be smaller than breaking at a nested comma.
1290 return 150;
1291 }
1292
1293 // In for-loops, prefer breaking at ',' and ';'.
1294 if (Line.First.is(tok::kw_for) &&
1295 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
1296 return 20;
1297
1298 if (Left.is(tok::semi) || Left.is(tok::comma))
1299 return 0;
1300
1301 // In Objective-C method expressions, prefer breaking before "param:" over
1302 // breaking after it.
1303 if (isObjCSelectorName(Right))
1304 return 0;
1305 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1306 return 20;
1307
1308 if (Left.is(tok::l_paren))
1309 return 20;
1310 // FIXME: The penalty for a trailing "<" or "[" being higher than the
1311 // penalty for a trainling "(" is a temporary workaround until we can
1312 // properly avoid breaking in array subscripts or template parameters.
1313 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
1314 return 50;
1315
1316 if (Left.Type == TT_ConditionalExpr)
1317 return prec::Assignment;
1318 prec::Level Level = getPrecedence(Left);
1319
1320 if (Level != prec::Unknown)
1321 return Level;
1322
1323 return 3;
1324 }
1325
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001326 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression,
1327 bool LookForFunctionName) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001328 if (getPrecedence(Current) == prec::Assignment) {
1329 IsExpression = true;
1330 AnnotatedToken *Previous = Current.Parent;
1331 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001332 if (Previous->Type == TT_BinaryOperator &&
1333 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001334 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001335 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001336 Previous = Previous->Parent;
1337 }
1338 }
1339 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001340 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1341 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001342 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001343
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001344 if (Current.Type == TT_Unknown) {
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001345 if (LookForFunctionName && Current.is(tok::l_paren)) {
1346 findFunctionName(&Current);
1347 LookForFunctionName = false;
1348 } else if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001349 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001350 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1351 Current.is(tok::caret)) {
1352 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001353 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1354 Current.Type = determineIncrementUsage(Current);
1355 } else if (Current.is(tok::exclaim)) {
1356 Current.Type = TT_UnaryOperator;
1357 } else if (isBinaryOperator(Current)) {
1358 Current.Type = TT_BinaryOperator;
1359 } else if (Current.is(tok::comment)) {
1360 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1361 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001362 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001363 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001364 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001365 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001366 } else if (Current.is(tok::r_paren) &&
1367 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001368 Current.Parent->Type == TT_TemplateCloser) &&
1369 (Current.Children.empty() ||
1370 (Current.Children[0].isNot(tok::equal) &&
1371 Current.Children[0].isNot(tok::semi) &&
1372 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001373 // FIXME: We need to get smarter and understand more cases of casts.
1374 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001375 } else if (Current.is(tok::at) && Current.Children.size()) {
1376 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1377 case tok::objc_interface:
1378 case tok::objc_implementation:
1379 case tok::objc_protocol:
1380 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001381 break;
1382 case tok::objc_property:
1383 Current.Type = TT_ObjCProperty;
1384 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001385 default:
1386 break;
1387 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001388 }
1389 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001390
1391 if (!Current.Children.empty())
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001392 determineTokenTypes(Current.Children[0], IsExpression,
1393 LookForFunctionName);
1394 }
1395
1396 /// \brief Starting from \p Current, this searches backwards for an
1397 /// identifier which could be the start of a function name and marks it.
1398 void findFunctionName(AnnotatedToken *Current) {
1399 AnnotatedToken *Parent = Current->Parent;
1400 while (Parent != NULL && Parent->Parent != NULL) {
1401 if (Parent->is(tok::identifier) &&
1402 (Parent->Parent->is(tok::identifier) ||
1403 Parent->Parent->Type == TT_PointerOrReference ||
1404 Parent->Parent->Type == TT_TemplateCloser)) {
1405 Parent->Type = TT_StartOfName;
1406 break;
1407 }
1408 Parent = Parent->Parent;
1409 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001410 }
1411
Daniel Jasper71945272013-01-15 14:27:39 +00001412 /// \brief Returns the previous token ignoring comments.
1413 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1414 const AnnotatedToken *PrevToken = Tok.Parent;
1415 while (PrevToken != NULL && PrevToken->is(tok::comment))
1416 PrevToken = PrevToken->Parent;
1417 return PrevToken;
1418 }
1419
1420 /// \brief Returns the next token ignoring comments.
1421 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1422 if (Tok.Children.empty())
1423 return NULL;
1424 const AnnotatedToken *NextToken = &Tok.Children[0];
1425 while (NextToken->is(tok::comment)) {
1426 if (NextToken->Children.empty())
1427 return NULL;
1428 NextToken = &NextToken->Children[0];
1429 }
1430 return NextToken;
1431 }
1432
1433 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasperbbc84152013-01-29 11:27:30 +00001434 TokenType
1435 determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001436 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1437 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001438 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001439
1440 const AnnotatedToken *NextToken = getNextToken(Tok);
1441 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001442 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001443
Daniel Jasper0b820602013-01-22 11:46:26 +00001444 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1445 return TT_PointerOrReference;
1446
Daniel Jasper71945272013-01-15 14:27:39 +00001447 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1448 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1449 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1450 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001451 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001452 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001453
Daniel Jasper71945272013-01-15 14:27:39 +00001454 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1455 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1456 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1457 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1458 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1459 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1460 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001461 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001462
Daniel Jasper71945272013-01-15 14:27:39 +00001463 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1464 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001465 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001466
Daniel Jasper426702d2012-12-05 07:51:39 +00001467 // It is very unlikely that we are going to find a pointer or reference type
1468 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001469 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001470 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001471
Daniel Jasperda16db32013-01-07 10:48:50 +00001472 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001473 }
1474
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001475 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001476 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1477 if (PrevToken == NULL)
1478 return TT_UnaryOperator;
1479
Daniel Jasper8dd40472012-12-21 09:41:31 +00001480 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001481 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1482 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1483 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1484 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1485 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001486 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001487
1488 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001489 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001490 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001491
1492 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001493 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001494 }
1495
1496 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001497 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001498 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1499 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001500 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001501 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1502 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001503 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001504
Daniel Jasperda16db32013-01-07 10:48:50 +00001505 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001506 }
1507
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001508 bool spaceRequiredBetween(const AnnotatedToken &Left,
1509 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001510 if (Right.is(tok::hashhash))
1511 return Left.is(tok::hash);
1512 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1513 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001514 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1515 return false;
Nico Webera6087752013-01-10 20:12:55 +00001516 if (Right.is(tok::less) &&
1517 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001518 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001519 return true;
1520 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1521 return false;
1522 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1523 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001524 if (Left.is(tok::at) &&
1525 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1526 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001527 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1528 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001529 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001530 if (Left.is(tok::coloncolon))
1531 return false;
1532 if (Right.is(tok::coloncolon))
1533 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001534 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1535 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001536 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001537 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001538 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1539 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001540 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001541 return Right.FormatTok.Tok.isLiteral() ||
1542 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001543 if (Right.is(tok::star) && Left.is(tok::l_paren))
1544 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001545 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1546 return false;
1547 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001548 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001549 if (Left.is(tok::period) || Right.is(tok::period))
1550 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001551 if (Left.is(tok::colon))
1552 return Left.Type != TT_ObjCMethodExpr;
1553 if (Right.is(tok::colon))
1554 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001555 if (Left.is(tok::l_paren))
1556 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001557 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001558 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001559 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001560 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001561 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1562 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001563 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001564 if (Left.is(tok::at) &&
1565 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001566 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001567 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1568 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001569 return true;
1570 }
1571
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001572 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001573 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1575 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001576 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001577 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001578 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001579 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001580 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001581 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001582 // Don't space between ')' and <id>
1583 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001584 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001585 // Don't space between ':' and '('
1586 return false;
1587 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001588 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001589 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1590 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001591
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001592 if (Tok.Parent->is(tok::comma))
1593 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001594 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001595 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001596 if (Tok.Type == TT_OverloadedOperator)
1597 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001598 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001599 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001600 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001601 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001602 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001603 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001604 if (Tok.Parent->Type == TT_UnaryOperator ||
1605 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001606 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001607 if (Tok.Type == TT_UnaryOperator)
1608 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001609 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1610 (Tok.Parent->isNot(tok::colon) ||
1611 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001612 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1613 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001614 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1615 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001616 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001617 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001618 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001619 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001620 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001621 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001622 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001623 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001624 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001625 }
1626
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001627 bool canBreakBefore(const AnnotatedToken &Right) {
1628 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001629 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001630 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1631 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001632 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001633 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1634 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001635 // Don't break this identifier as ':' or identifier
1636 // before it will break.
1637 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001638 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1639 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001640 // Don't break at ':' if identifier before it can beak.
1641 return false;
1642 }
Daniel Jasperd36ef5e2013-01-28 15:40:20 +00001643 if (Right.Type == TT_StartOfName && Style.AllowReturnTypeOnItsOwnLine)
Daniel Jasperd2639ef2013-01-28 15:16:31 +00001644 return true;
Nico Webera7252d82013-01-12 06:18:40 +00001645 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1646 return false;
1647 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1648 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001649 if (isObjCSelectorName(Right))
1650 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001651 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001652 return true;
Daniel Jasperca6623b2013-01-28 12:45:14 +00001653 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1654 return true;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001655 if (Left.Type == TT_RangeBasedForLoopColon)
1656 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001657 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperca6623b2013-01-28 12:45:14 +00001658 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1659 Left.is(tok::question))
Daniel Jasperd1926a32013-01-02 08:44:14 +00001660 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001661 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001662 return false;
1663
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001664 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001665 // We rely on MustBreakBefore being set correctly here as we should not
1666 // change the "binding" behavior of a comment.
1667 return false;
1668
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001669 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1670 // unless it is follow by ';', '{' or '='.
1671 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1672 Left.Parent->is(tok::r_paren))
1673 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1674 Right.isNot(tok::equal);
1675
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001676 // We only break before r_brace if there was a corresponding break before
1677 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1678 if (Right.is(tok::r_brace))
1679 return false;
1680
Daniel Jasper71945272013-01-15 14:27:39 +00001681 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001682 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001683 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1684 Left.is(tok::comma) || Right.is(tok::lessless) ||
1685 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001686 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1687 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001688 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1689 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001690 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1691 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001692 }
1693
Daniel Jasperf7935112012-12-03 18:12:45 +00001694 FormatStyle Style;
1695 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001696 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001697 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001698};
1699
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001700class LexerBasedFormatTokenSource : public FormatTokenSource {
1701public:
1702 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001703 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001704 IdentTable(Lex.getLangOpts()) {
1705 Lex.SetKeepWhitespaceMode(true);
1706 }
1707
1708 virtual FormatToken getNextToken() {
1709 if (GreaterStashed) {
1710 FormatTok.NewlinesBefore = 0;
1711 FormatTok.WhiteSpaceStart =
1712 FormatTok.Tok.getLocation().getLocWithOffset(1);
1713 FormatTok.WhiteSpaceLength = 0;
1714 GreaterStashed = false;
1715 return FormatTok;
1716 }
1717
1718 FormatTok = FormatToken();
1719 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001720 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001721 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001722 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1723 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001724
1725 // Consume and record whitespace until we find a significant token.
1726 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001727 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasperbbc84152013-01-29 11:27:30 +00001728 FormatTok.HasUnescapedNewline =
1729 Text.count("\\\n") != FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001730 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1731
1732 if (FormatTok.Tok.is(tok::eof))
1733 return FormatTok;
1734 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001735 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001736 }
Manuel Klimekef920692013-01-07 07:56:50 +00001737
1738 // Now FormatTok is the next non-whitespace token.
1739 FormatTok.TokenLength = Text.size();
1740
Manuel Klimek1abf7892013-01-04 23:34:14 +00001741 // In case the token starts with escaped newlines, we want to
1742 // take them into account as whitespace - this pattern is quite frequent
1743 // in macro definitions.
1744 // FIXME: What do we want to do with other escaped spaces, and escaped
1745 // spaces or newlines in the middle of tokens?
1746 // FIXME: Add a more explicit test.
1747 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001748 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001749 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001750 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001751 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001752 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001753 }
1754
1755 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001756 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001757 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001758 FormatTok.Tok.setKind(Info.getTokenID());
1759 }
1760
1761 if (FormatTok.Tok.is(tok::greatergreater)) {
1762 FormatTok.Tok.setKind(tok::greater);
1763 GreaterStashed = true;
1764 }
1765
1766 return FormatTok;
1767 }
1768
1769private:
1770 FormatToken FormatTok;
1771 bool GreaterStashed;
1772 Lexer &Lex;
1773 SourceManager &SourceMgr;
1774 IdentifierTable IdentTable;
1775
1776 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001777 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001778 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1779 Tok.getLength());
1780 }
1781};
1782
Daniel Jasperf7935112012-12-03 18:12:45 +00001783class Formatter : public UnwrappedLineConsumer {
1784public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001785 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1786 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001787 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001788 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001789 Whitespaces(SourceMgr), Ranges(Ranges) {
1790 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001791
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001792 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001793
Daniel Jasperf7935112012-12-03 18:12:45 +00001794 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001795 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001796 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001797 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001798 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001799 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1800 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1801 Annotator.annotate();
1802 }
1803 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1804 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001805 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001806 const AnnotatedLine &TheLine = *I;
1807 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
Daniel Jasperbbc84152013-01-29 11:27:30 +00001808 unsigned Indent =
1809 formatFirstToken(TheLine.First, TheLine.Level,
1810 TheLine.InPPDirective, PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001811 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001812 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001813 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001814 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001815 PreviousEndOfLineColumn = Formatter.format();
1816 } else {
1817 // If we did not reformat this unwrapped line, the column at the end of
1818 // the last token is unchanged - thus, we can calculate the end of the
1819 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001820 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001821 SourceMgr.getSpellingColumnNumber(
1822 TheLine.Last->FormatTok.Tok.getLocation()) +
1823 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
Daniel Jasperbbc84152013-01-29 11:27:30 +00001824 SourceMgr, Lex.getLangOpts()) - 1;
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001825 }
1826 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001827 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001828 }
1829
1830private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001831 /// \brief Tries to merge lines into one.
1832 ///
1833 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1834 /// if possible; note that \c I will be incremented when lines are merged.
1835 ///
1836 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001837 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001838 std::vector<AnnotatedLine>::iterator &I,
1839 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001840 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1841
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001842 // We can never merge stuff if there are trailing line comments.
1843 if (I->Last->Type == TT_LineComment)
1844 return;
1845
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001846 // Check whether the UnwrappedLine can be put onto a single line. If
1847 // so, this is bound to be the optimal solution (by definition) and we
1848 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001849 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001850 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001851 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001852
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001853 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001854 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001855
Daniel Jasper25837aa2013-01-14 14:14:23 +00001856 if (I->Last->is(tok::l_brace)) {
1857 tryMergeSimpleBlock(I, E, Limit);
1858 } else if (I->First.is(tok::kw_if)) {
1859 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001860 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1861 I->First.FormatTok.IsFirst)) {
1862 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001863 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001864 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001865 }
1866
Daniel Jasper39825ea2013-01-14 15:40:57 +00001867 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1868 std::vector<AnnotatedLine>::iterator E,
1869 unsigned Limit) {
1870 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001871 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1872 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001873 if (I + 2 != E && (I + 2)->InPPDirective &&
1874 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1875 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001876 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001877 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001878 join(Line, *(++I));
1879 }
1880
Daniel Jasper25837aa2013-01-14 14:14:23 +00001881 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1882 std::vector<AnnotatedLine>::iterator E,
1883 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001884 if (!Style.AllowShortIfStatementsOnASingleLine)
1885 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001886 if ((I + 1)->InPPDirective != I->InPPDirective ||
1887 ((I + 1)->InPPDirective &&
1888 (I + 1)->First.FormatTok.HasUnescapedNewline))
1889 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001890 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001891 if (Line.Last->isNot(tok::r_paren))
1892 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001893 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001894 return;
1895 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1896 return;
1897 // Only inline simple if's (no nested if or else).
1898 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1899 return;
1900 join(Line, *(++I));
1901 }
1902
1903 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
Daniel Jasperbbc84152013-01-29 11:27:30 +00001904 std::vector<AnnotatedLine>::iterator E,
1905 unsigned Limit) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001906 // First, check that the current line allows merging. This is the case if
1907 // we're not in a control flow statement and the last token is an opening
1908 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001909 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001910 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001911 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1912 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1913 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1914 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001915 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001916 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1917 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001918 if (!AllowedTokens)
1919 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001920
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001921 AnnotatedToken *Tok = &(I + 1)->First;
1922 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1923 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1924 Tok->SpaceRequiredBefore = false;
1925 join(Line, *(I + 1));
1926 I += 1;
1927 } else {
1928 // Check that we still have three lines and they fit into the limit.
1929 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1930 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001931 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001932
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001933 // Second, check that the next line does not contain any braces - if it
1934 // does, readability declines when putting it into a single line.
1935 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1936 return;
1937 do {
1938 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1939 return;
1940 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1941 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001942
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001943 // Last, check that the third line contains a single closing brace.
1944 Tok = &(I + 2)->First;
1945 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1946 Tok->MustBreakBefore)
1947 return;
1948
1949 join(Line, *(I + 1));
1950 join(Line, *(I + 2));
1951 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001952 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001953 }
1954
1955 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1956 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001957 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1958 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001959 }
1960
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001961 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1962 A.Last->Children.push_back(B.First);
1963 while (!A.Last->Children.empty()) {
1964 A.Last->Children[0].Parent = A.Last;
1965 A.Last = &A.Last->Children[0];
1966 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001967 }
1968
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001969 bool touchesRanges(const AnnotatedLine &TheLine) {
1970 const FormatToken *First = &TheLine.First.FormatTok;
1971 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001972 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasperbbc84152013-01-29 11:27:30 +00001973 First->Tok.getLocation(), Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001974 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001975 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1976 Ranges[i].getBegin()) &&
1977 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1978 LineRange.getBegin()))
1979 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001980 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001981 return false;
1982 }
1983
1984 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001985 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001986 }
1987
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001988 /// \brief Add a new line and the required indent before the first Token
1989 /// of the \c UnwrappedLine if there was no structural parsing error.
1990 /// Returns the indent level of the \c UnwrappedLine.
1991 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1992 bool InPPDirective,
1993 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001994 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001995 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1996 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1997
Daniel Jasperbbc84152013-01-29 11:27:30 +00001998 unsigned Newlines =
1999 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002000 if (Newlines == 0 && !Tok.IsFirst)
2001 Newlines = 1;
2002 unsigned Indent = Level * 2;
2003
2004 bool IsAccessModifier = false;
2005 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
2006 RootToken.is(tok::kw_private))
2007 IsAccessModifier = true;
2008 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
2009 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
2010 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
2011 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
2012 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
2013 IsAccessModifier = true;
2014
2015 if (IsAccessModifier &&
2016 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
2017 Indent += Style.AccessModifierOffset;
2018 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002019 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002020 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002021 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
2022 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00002023 }
2024 return Indent;
2025 }
2026
Alexander Kornienko116ba682013-01-14 11:34:14 +00002027 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00002028 FormatStyle Style;
2029 Lexer &Lex;
2030 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00002031 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00002032 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00002033 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00002034 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00002035};
2036
Daniel Jasperbbc84152013-01-29 11:27:30 +00002037tooling::Replacements
2038reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
2039 std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002040 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00002041 OwningPtr<DiagnosticConsumer> DiagPrinter;
2042 if (DiagClient == 0) {
2043 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
2044 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
2045 DiagClient = DiagPrinter.get();
2046 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002047 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002048 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002049 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002050 Diagnostics.setSourceManager(&SourceMgr);
2051 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002052 return formatter.format();
2053}
2054
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002055LangOptions getFormattingLangOpts() {
2056 LangOptions LangOpts;
2057 LangOpts.CPlusPlus = 1;
2058 LangOpts.CPlusPlus11 = 1;
2059 LangOpts.Bool = 1;
2060 LangOpts.ObjC1 = 1;
2061 LangOpts.ObjC2 = 1;
2062 return LangOpts;
2063}
2064
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002065} // namespace format
2066} // namespace clang