blob: 27d47109bd88dcc609344290e3ad1aa3e5b9660e [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,
Daniel Jasper0b41cbb2013-01-28 13:21:16 +000043 TT_RangeBasedForLoopColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000044 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000045 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000046 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000047 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000048 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000049 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000050 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000051 TT_OverloadedOperator,
52 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000053 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000054 TT_TemplateCloser,
55 TT_TemplateOpener,
56 TT_TrailingUnaryOperator,
57 TT_UnaryOperator,
58 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000059};
60
61enum LineType {
62 LT_Invalid,
63 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000064 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000065 LT_PreprocessorDirective,
66 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000067 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000068 LT_ObjCMethodDecl,
69 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000070};
71
Daniel Jasper7c85fde2013-01-08 14:56:18 +000072class AnnotatedToken {
73public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000074 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000075 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
76 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000077 ClosesTemplateDeclaration(false), MatchingParen(NULL),
78 ParameterCount(1), Parent(NULL) {
79 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000080
Daniel Jasper25837aa2013-01-14 14:14:23 +000081 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
82 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
83
Daniel Jasper7c85fde2013-01-08 14:56:18 +000084 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
85 return FormatTok.Tok.isObjCAtKeyword(Kind);
86 }
87
88 FormatToken FormatTok;
89
Daniel Jasperf7935112012-12-03 18:12:45 +000090 TokenType Type;
91
Daniel Jasperf7935112012-12-03 18:12:45 +000092 bool SpaceRequiredBefore;
93 bool CanBreakBefore;
94 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000095
96 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000097
Daniel Jasper9278eb92013-01-16 14:59:02 +000098 AnnotatedToken *MatchingParen;
99
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000100 /// \brief Number of parameters, if this is "(", "[" or "<".
101 ///
102 /// This is initialized to 1 as we don't need to distinguish functions with
103 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
104 /// the number of commas.
105 unsigned ParameterCount;
106
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000107 /// \brief The total length of the line up to and including this token.
108 unsigned TotalLength;
109
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000110 std::vector<AnnotatedToken> Children;
111 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000112
113 const AnnotatedToken *getPreviousNoneComment() const {
114 AnnotatedToken *Tok = Parent;
115 while (Tok != NULL && Tok->is(tok::comment))
116 Tok = Tok->Parent;
117 return Tok;
118 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000119};
120
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000121class AnnotatedLine {
122public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000123 AnnotatedLine(const UnwrappedLine &Line)
124 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000125 InPPDirective(Line.InPPDirective),
126 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000127 assert(!Line.Tokens.empty());
128 AnnotatedToken *Current = &First;
129 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
130 E = Line.Tokens.end();
131 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000132 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000133 Current->Children[0].Parent = Current;
134 Current = &Current->Children[0];
135 }
136 Last = Current;
137 }
138 AnnotatedLine(const AnnotatedLine &Other)
139 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000140 InPPDirective(Other.InPPDirective),
141 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000142 Last = &First;
143 while (!Last->Children.empty()) {
144 Last->Children[0].Parent = Last;
145 Last = &Last->Children[0];
146 }
147 }
148
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000149 AnnotatedToken First;
150 AnnotatedToken *Last;
151
152 LineType Type;
153 unsigned Level;
154 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000155 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000156};
157
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000158static prec::Level getPrecedence(const AnnotatedToken &Tok) {
159 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000160}
161
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000162bool isBinaryOperator(const AnnotatedToken &Tok) {
163 // Comma is a binary operator, but does not behave as such wrt. formatting.
164 return getPrecedence(Tok) > prec::Comma;
165}
166
Daniel Jasperf7935112012-12-03 18:12:45 +0000167FormatStyle getLLVMStyle() {
168 FormatStyle LLVMStyle;
169 LLVMStyle.ColumnLimit = 80;
170 LLVMStyle.MaxEmptyLinesToKeep = 1;
171 LLVMStyle.PointerAndReferenceBindToType = false;
172 LLVMStyle.AccessModifierOffset = -2;
173 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000174 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000175 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000176 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000177 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000178 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000179 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000180 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000181 return LLVMStyle;
182}
183
184FormatStyle getGoogleStyle() {
185 FormatStyle GoogleStyle;
186 GoogleStyle.ColumnLimit = 80;
187 GoogleStyle.MaxEmptyLinesToKeep = 1;
188 GoogleStyle.PointerAndReferenceBindToType = true;
189 GoogleStyle.AccessModifierOffset = -1;
190 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000191 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000192 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000193 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000194 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000195 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000196 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000197 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000198 return GoogleStyle;
199}
200
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000201FormatStyle getChromiumStyle() {
202 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000203 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000204 return ChromiumStyle;
205}
206
Daniel Jasperf7935112012-12-03 18:12:45 +0000207struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000208 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +0000209 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000210};
211
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000213///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000214/// This includes special handling for certain constructs, e.g. the alignment of
215/// trailing line comments.
216class WhitespaceManager {
217public:
218 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
219
220 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
221 /// each \c AnnotatedToken.
222 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
223 unsigned Spaces, unsigned WhitespaceStartColumn,
224 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000225 // 2+ newlines mean an empty line separating logic scopes.
226 if (NewLines >= 2)
227 alignComments();
228
229 // Align line comments if they are trailing or if they continue other
230 // trailing comments.
231 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000232 (Tok.Parent != NULL || !Comments.empty())) {
233 if (Style.ColumnLimit >=
234 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
235 Comments.push_back(StoredComment());
236 Comments.back().Tok = Tok.FormatTok;
237 Comments.back().Spaces = Spaces;
238 Comments.back().NewLines = NewLines;
239 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
240 Comments.back().MaxColumn = Style.ColumnLimit -
241 Spaces - Tok.FormatTok.TokenLength;
242 return;
243 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000244 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000245
246 // If this line does not have a trailing comment, align the stored comments.
247 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
248 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000249 storeReplacement(Tok.FormatTok,
250 std::string(NewLines, '\n') + std::string(Spaces, ' '));
251 }
252
253 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
254 /// backslashes to escape newlines inside a preprocessor directive.
255 ///
256 /// This function and \c replaceWhitespace have the same behavior if
257 /// \c Newlines == 0.
258 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
259 unsigned Spaces, unsigned WhitespaceStartColumn,
260 const FormatStyle &Style) {
261 std::string NewLineText;
262 if (NewLines > 0) {
263 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
264 WhitespaceStartColumn);
265 for (unsigned i = 0; i < NewLines; ++i) {
266 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
267 NewLineText += "\\\n";
268 Offset = 0;
269 }
270 }
271 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
272 }
273
274 /// \brief Returns all the \c Replacements created during formatting.
275 const tooling::Replacements &generateReplacements() {
276 alignComments();
277 return Replaces;
278 }
279
280private:
281 /// \brief Structure to store a comment for later layout and alignment.
282 struct StoredComment {
283 FormatToken Tok;
284 unsigned MinColumn;
285 unsigned MaxColumn;
286 unsigned NewLines;
287 unsigned Spaces;
288 };
289 SmallVector<StoredComment, 16> Comments;
290 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
291
292 /// \brief Try to align all stashed comments.
293 void alignComments() {
294 unsigned MinColumn = 0;
295 unsigned MaxColumn = UINT_MAX;
296 comment_iterator Start = Comments.begin();
297 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
298 ++I) {
299 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
300 alignComments(Start, I, MinColumn);
301 MinColumn = I->MinColumn;
302 MaxColumn = I->MaxColumn;
303 Start = I;
304 } else {
305 MinColumn = std::max(MinColumn, I->MinColumn);
306 MaxColumn = std::min(MaxColumn, I->MaxColumn);
307 }
308 }
309 alignComments(Start, Comments.end(), MinColumn);
310 Comments.clear();
311 }
312
313 /// \brief Put all the comments between \p I and \p E into \p Column.
314 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
315 while (I != E) {
316 unsigned Spaces = I->Spaces + Column - I->MinColumn;
317 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
318 std::string(Spaces, ' '));
319 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000320 }
321 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000322
323 /// \brief Stores \p Text as the replacement for the whitespace in front of
324 /// \p Tok.
325 void storeReplacement(const FormatToken &Tok, const std::string Text) {
326 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
327 Tok.WhiteSpaceLength, Text));
328 }
329
330 SourceManager &SourceMgr;
331 tooling::Replacements Replaces;
332};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000333
Nico Weberc9d73612013-01-12 22:48:47 +0000334/// \brief Returns if a token is an Objective-C selector name.
335///
Nico Weber92c05392013-01-12 22:51:13 +0000336/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000337static bool isObjCSelectorName(const AnnotatedToken &Tok) {
338 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
339 Tok.Children[0].is(tok::colon) &&
340 Tok.Children[0].Type == TT_ObjCMethodExpr;
341}
342
Daniel Jasperf7935112012-12-03 18:12:45 +0000343class UnwrappedLineFormatter {
344public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000345 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000346 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000347 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000348 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000349 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000350 FirstIndent(FirstIndent), RootToken(RootToken),
351 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000352 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000353 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000354 }
355
Manuel Klimek1abf7892013-01-04 23:34:14 +0000356 /// \brief Formats an \c UnwrappedLine.
357 ///
358 /// \returns The column after the last token in the last line of the
359 /// \c UnwrappedLine.
360 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000361 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000362 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000363 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000364 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000365 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000366 State.ForLoopVariablePos = 0;
367 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000368
Manuel Klimek24998102013-01-16 14:55:28 +0000369 DEBUG({
370 DebugTokenState(*State.NextToken);
371 });
372
Daniel Jaspere9de2602012-12-06 09:56:08 +0000373 // The first token has already been indented and thus consumed.
374 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000375
376 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000377 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000378 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
379 // Calculating the column is important for aligning trailing comments.
380 // FIXME: This does not seem to happen in conjunction with escaped
381 // newlines. If it does, fix!
382 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
383 State.NextToken->FormatTok.TokenLength;
384 State.NextToken = State.NextToken->Children.empty() ? NULL :
385 &State.NextToken->Children[0];
386 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000387 addTokenToState(false, false, State);
388 } else {
389 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
390 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000391 DEBUG({
392 if (Break < NoBreak)
393 llvm::errs() << "\n";
394 else
395 llvm::errs() << " ";
396 llvm::errs() << "<";
397 DebugPenalty(Break, Break < NoBreak);
398 llvm::errs() << "/";
399 DebugPenalty(NoBreak, !(Break < NoBreak));
400 llvm::errs() << "> ";
401 DebugTokenState(*State.NextToken);
402 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000403 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000404 if (State.NextToken != NULL &&
405 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
406 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000407 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000408 State.Stack.back().BreakAfterComma = true;
409 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000410 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
Manuel Klimek24998102013-01-16 14:55:28 +0000412 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000413 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000414 }
415
416private:
Manuel Klimek24998102013-01-16 14:55:28 +0000417 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
418 const Token &Tok = AnnotatedTok.FormatTok.Tok;
419 llvm::errs()
420 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
421 Tok.getLength());
422 llvm::errs();
423 }
424
425 void DebugPenalty(unsigned Penalty, bool Winner) {
426 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
427 if (Penalty == UINT_MAX)
428 llvm::errs() << "MAX";
429 else
430 llvm::errs() << Penalty;
431 llvm::errs().resetColor();
432 }
433
Daniel Jasper337816e2013-01-11 10:22:12 +0000434 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000435 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000436 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000437 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jaspera836b902013-01-23 16:58:21 +0000438 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000439
Daniel Jasperf7935112012-12-03 18:12:45 +0000440 /// \brief The position to which a specific parenthesis level needs to be
441 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000442 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000443
Daniel Jaspere9de2602012-12-06 09:56:08 +0000444 /// \brief The position of the last space on each level.
445 ///
446 /// Used e.g. to break like:
447 /// functionCall(Parameter, otherCall(
448 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000450
Daniel Jaspera836b902013-01-23 16:58:21 +0000451 /// \brief This is the column of the first token after an assignment.
452 unsigned AssignmentColumn;
453
Daniel Jaspere9de2602012-12-06 09:56:08 +0000454 /// \brief The position the first "<<" operator encountered on each level.
455 ///
456 /// Used to align "<<" operators. 0 if no such operator has been encountered
457 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000459
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000460 /// \brief Whether a newline needs to be inserted before the block's closing
461 /// brace.
462 ///
463 /// We only want to insert a newline before the closing brace if there also
464 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 bool BreakBeforeClosingBrace;
466
Daniel Jasperca6623b2013-01-28 12:45:14 +0000467 /// \brief The column of a \c ? in a conditional expression;
468 unsigned QuestionColumn;
469
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000470 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000471 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000472
Daniel Jasper337816e2013-01-11 10:22:12 +0000473 bool operator<(const ParenState &Other) const {
474 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000475 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000476 if (LastSpace != Other.LastSpace)
477 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000478 if (AssignmentColumn != Other.AssignmentColumn)
479 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000480 if (FirstLessLess != Other.FirstLessLess)
481 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000482 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
483 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000484 if (QuestionColumn != Other.QuestionColumn)
485 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000486 if (BreakAfterComma != Other.BreakAfterComma)
487 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000488 if (HasMultiParameterLine != Other.HasMultiParameterLine)
489 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000490 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000491 }
492 };
493
494 /// \brief The current state when indenting a unwrapped line.
495 ///
496 /// As the indenting tries different combinations this is copied by value.
497 struct LineState {
498 /// \brief The number of used columns in the current line.
499 unsigned Column;
500
501 /// \brief The token that needs to be next formatted.
502 const AnnotatedToken *NextToken;
503
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000504 /// \brief The column of the first variable in a for-loop declaration.
505 ///
506 /// Used to align the second variable if necessary.
507 unsigned ForLoopVariablePos;
508
509 /// \brief \c true if this line contains a continued for-loop section.
510 bool LineContainsContinuedForLoopSection;
511
Daniel Jasper337816e2013-01-11 10:22:12 +0000512 /// \brief A stack keeping track of properties applying to parenthesis
513 /// levels.
514 std::vector<ParenState> Stack;
515
516 /// \brief Comparison operator to be able to used \c LineState in \c map.
517 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000518 if (Other.NextToken != NextToken)
519 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000520 if (Other.Column != Column)
521 return Other.Column > Column;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000522 if (Other.ForLoopVariablePos != ForLoopVariablePos)
523 return Other.ForLoopVariablePos < ForLoopVariablePos;
524 if (Other.LineContainsContinuedForLoopSection !=
525 LineContainsContinuedForLoopSection)
526 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000527 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000528 }
529 };
530
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000531 /// \brief Appends the next token to \p State and updates information
532 /// necessary for indentation.
533 ///
534 /// Puts the token on the current line if \p Newline is \c true and adds a
535 /// line break and necessary indentation otherwise.
536 ///
537 /// If \p DryRun is \c false, also creates and stores the required
538 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000540 const AnnotatedToken &Current = *State.NextToken;
541 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000542 assert(State.Stack.size());
543 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000544
545 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000546 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000547 if (Current.is(tok::r_brace)) {
548 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000549 } else if (Current.is(tok::string_literal) &&
550 Previous.is(tok::string_literal)) {
551 State.Column = State.Column - Previous.FormatTok.TokenLength;
552 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000553 State.Stack[ParenLevel].FirstLessLess != 0) {
554 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000555 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000556 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000557 Current.is(tok::period) || Current.is(tok::arrow) ||
558 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000559 // Indent and extra 4 spaces after if we know the current expression is
560 // continued. Don't do that on the top level, as we already indent 4
561 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000562 State.Column = std::max(State.Stack.back().LastSpace,
563 State.Stack.back().Indent) + 4;
564 } else if (Current.Type == TT_ConditionalExpr) {
565 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000566 } else if (RootToken.is(tok::kw_for) && ParenLevel == 1 &&
567 Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000568 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000569 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000570 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000571 } else if (Previous.Type == TT_BinaryOperator &&
572 State.Stack.back().AssignmentColumn != 0) {
573 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000574 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000575 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000576 }
577
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000578 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000579 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000580
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000581 if (!DryRun) {
582 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000583 Whitespaces.replaceWhitespace(Current, 1, State.Column,
584 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000585 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000586 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
587 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000588 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000589
Daniel Jasper337816e2013-01-11 10:22:12 +0000590 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000591 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000592 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000593 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000594 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
595 State.ForLoopVariablePos = State.Column -
596 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000597
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000598 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
599 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000600 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000601
Daniel Jasperf7935112012-12-03 18:12:45 +0000602 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000603 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000604
Daniel Jasperbcab4302013-01-09 10:40:23 +0000605 // FIXME: Do we need to do this for assignments nested in other
606 // expressions?
607 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000608 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000609 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000610 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000611 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000612 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000613 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000614 if (Current.getPreviousNoneComment() != NULL &&
615 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000616 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000617 State.Stack[ParenLevel].HasMultiParameterLine = true;
618
Daniel Jaspere9de2602012-12-06 09:56:08 +0000619 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000620 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
621 // Treat the condition inside an if as if it was a second function
622 // parameter, i.e. let nested calls have an indent of 4.
623 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000624 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000625 // Top-level spaces are exempt as that mostly leads to better results.
626 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000627 else if ((Previous.Type == TT_BinaryOperator ||
Daniel Jasper65585ed2013-01-28 13:31:35 +0000628 Previous.Type == TT_ConditionalExpr ||
629 Previous.Type == TT_CtorInitializerColon) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000630 getPrecedence(Previous) != prec::Assignment)
631 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000632 else if (Previous.ParameterCount > 1 &&
633 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
634 Previous.Type == TT_TemplateOpener))
635 // If this function has multiple parameters, indent nested calls from
636 // the start of the first parameter.
637 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000638 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000639
640 // If we break after an {, we should also break before the corresponding }.
641 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000642 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000643
Daniel Jaspere941b162013-01-23 10:08:28 +0000644 if (!Style.BinPackParameters && Newline) {
645 // If we are breaking after '(', '{', '<', this is not bin packing unless
646 // AllowAllParametersOnNextLine is false.
647 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
648 Previous.Type != TT_TemplateOpener) ||
649 !Style.AllowAllParametersOnNextLine)
650 State.Stack.back().BreakAfterComma = true;
651
652 // Any break on this level means that the parent level has been broken
653 // and we need to avoid bin packing there.
654 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
655 State.Stack[i].BreakAfterComma = true;
656 }
657 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000658
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000659 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000660 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000661
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000662 /// \brief Mark the next token as consumed in \p State and modify its stacks
663 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000664 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000665 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000666 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000667
Daniel Jasper337816e2013-01-11 10:22:12 +0000668 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
669 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000670 if (Current.is(tok::question))
671 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000672
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000673 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000674 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000675 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
676 Current.is(tok::l_brace) ||
677 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000678 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000679 if (Current.is(tok::l_brace)) {
680 // FIXME: This does not work with nested static initializers.
681 // Implement a better handling for static initializers and similar
682 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000683 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000684 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000685 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000686 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000687 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000688 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000689 }
690
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000691 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000692 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000693 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
694 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
695 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000696 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000697 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000698
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000699 if (State.NextToken->Children.empty())
700 State.NextToken = NULL;
701 else
702 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000703
704 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000705 }
706
Nico Weber49cbc2c2013-01-07 15:15:29 +0000707 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000708 unsigned splitPenalty(const AnnotatedToken &Tok) {
709 const AnnotatedToken &Left = Tok;
710 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000711
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000712 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
713 return 50;
714 if (Left.is(tok::equal) && Right.is(tok::l_brace))
715 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000716 if (Left.is(tok::coloncolon))
717 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000718
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000719 if (Left.Type == TT_RangeBasedForLoopColon)
720 return 5;
721
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000722 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000723 if (RootToken.is(tok::kw_for) &&
724 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000725 return 20;
726
Daniel Jasper04468962013-01-18 10:56:38 +0000727 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000728 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000729
730 // In Objective-C method expressions, prefer breaking before "param:" over
731 // breaking after it.
732 if (isObjCSelectorName(Right))
733 return 0;
734 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
735 return 20;
736
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000737 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000738 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000739 // FIXME: The penalty for a trailing "<" or "[" being higher than the
740 // penalty for a trainling "(" is a temporary workaround until we can
741 // properly avoid breaking in array subscripts or template parameters.
742 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
743 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000744
Daniel Jasperca6623b2013-01-28 12:45:14 +0000745 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper399d24b2013-01-09 07:06:56 +0000746 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000747 prec::Level Level = getPrecedence(Left);
748
Daniel Jasperde5c2072012-12-24 00:13:23 +0000749 if (Level != prec::Unknown)
750 return Level;
751
Daniel Jasper04468962013-01-18 10:56:38 +0000752 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000753 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000754 return 5; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000755 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000756 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000757
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 return 3;
759 }
760
Daniel Jasper2df93312013-01-09 10:16:05 +0000761 unsigned getColumnLimit() {
762 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
763 }
764
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 /// \brief Calculate the number of lines needed to format the remaining part
766 /// of the unwrapped line.
767 ///
768 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000769 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000770 /// added after the previous token.
771 ///
772 /// \param StopAt is used for optimization. If we can determine that we'll
773 /// definitely need at least \p StopAt additional lines, we already know of a
774 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000775 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000776 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000777 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000778 return 0;
779
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000780 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000781 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000782 if (NewLine && !State.NextToken->CanBreakBefore &&
783 !(State.NextToken->is(tok::r_brace) &&
784 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000786 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000787 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000788 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000789 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000790 State.LineContainsContinuedForLoopSection)
791 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000792 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000793 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000794 State.Stack.back().BreakAfterComma)
795 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000796 // Trying to insert a parameter on a new line if there are already more than
797 // one parameter on the current line is bin packing.
798 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
799 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
800 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000801 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
802 (State.NextToken->Parent->ClosesTemplateDeclaration &&
803 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000804 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000805
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000806 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000807 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000808 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000809 splitPenalty(*State.NextToken->Parent);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000810
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000811 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000812
Daniel Jasper2df93312013-01-09 10:16:05 +0000813 // Exceeding column limit is bad, assign penalty.
814 if (State.Column > getColumnLimit()) {
815 unsigned ExcessCharacters = State.Column - getColumnLimit();
816 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
817 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000818
Daniel Jasperf7935112012-12-03 18:12:45 +0000819 if (StopAt <= CurrentPenalty)
820 return UINT_MAX;
821 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000822 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000823 if (I != Memory.end()) {
824 // If this state has already been examined, we can safely return the
825 // previous result if we
826 // - have not hit the optimatization (and thus returned UINT_MAX) OR
827 // - are now computing for a smaller or equal StopAt.
828 unsigned SavedResult = I->second.first;
829 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000830 if (SavedResult != UINT_MAX)
831 return SavedResult + CurrentPenalty;
832 else if (StopAt <= SavedStopAt)
833 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000834 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000835
836 unsigned NoBreak = calcPenalty(State, false, StopAt);
837 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
838 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000839
840 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
841 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000842 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000843
844 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000845 }
846
Daniel Jasperf7935112012-12-03 18:12:45 +0000847 FormatStyle Style;
848 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000849 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000850 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000851 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000852 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000853
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000854 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000855 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000856 StateMap Memory;
857
Daniel Jasperf7935112012-12-03 18:12:45 +0000858 OptimizationParameters Parameters;
859};
860
861/// \brief Determines extra information about the tokens comprising an
862/// \c UnwrappedLine.
863class TokenAnnotator {
864public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000865 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
866 AnnotatedLine &Line)
867 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000868
869 /// \brief A parser that gathers additional information about tokens.
870 ///
871 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
872 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
873 /// into template parameter lists.
874 class AnnotatingParser {
875 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000877 : CurrentToken(&RootToken), KeywordVirtualFound(false),
Daniel Jasper0b41cbb2013-01-28 13:21:16 +0000878 ColonIsObjCMethodExpr(false), ColonIsForRangeExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000879
Nico Weber250fe712013-01-18 02:43:57 +0000880 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
881 struct ObjCSelectorRAII {
882 AnnotatingParser &P;
883 bool ColonWasObjCMethodExpr;
884
885 ObjCSelectorRAII(AnnotatingParser &P)
886 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
887
888 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
889
890 void markStart(AnnotatedToken &Left) {
891 P.ColonIsObjCMethodExpr = true;
892 Left.Type = TT_ObjCMethodExpr;
893 }
894
895 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
896 };
897
898
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000899 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000900 if (CurrentToken == NULL)
901 return false;
902 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000903 while (CurrentToken != NULL) {
904 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000905 Left->MatchingParen = CurrentToken;
906 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000907 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000908 next();
909 return true;
910 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000911 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
912 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000913 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000914 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
915 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000916 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000917 if (CurrentToken->is(tok::comma))
918 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000919 if (!consumeToken())
920 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000921 }
922 return false;
923 }
924
Nico Weber80a82762013-01-17 17:17:19 +0000925 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000926 if (CurrentToken == NULL)
927 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000928 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000929 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000930 if (CurrentToken->is(tok::caret)) {
931 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000932 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000933 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
934 // @selector( starts a selector.
935 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
936 MaybeSel->Parent->is(tok::at)) {
937 StartsObjCMethodExpr = true;
938 }
939 }
940
941 ObjCSelectorRAII objCSelector(*this);
942 if (StartsObjCMethodExpr)
943 objCSelector.markStart(*Left);
944
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000945 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000946 // LookForDecls is set when "if (" has been seen. Check for
947 // 'identifier' '*' 'identifier' followed by not '=' -- this
948 // '*' has to be a binary operator but determineStarAmpUsage() will
949 // categorize it as an unary operator, so set the right type here.
950 if (LookForDecls && !CurrentToken->Children.empty()) {
951 AnnotatedToken &Prev = *CurrentToken->Parent;
952 AnnotatedToken &Next = CurrentToken->Children[0];
953 if (Prev.Parent->is(tok::identifier) &&
954 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
955 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
956 Prev.Type = TT_BinaryOperator;
957 LookForDecls = false;
958 }
959 }
960
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000962 Left->MatchingParen = CurrentToken;
963 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000964
965 if (StartsObjCMethodExpr)
966 objCSelector.markEnd(*CurrentToken);
967
Daniel Jasperf7935112012-12-03 18:12:45 +0000968 next();
969 return true;
970 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000971 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000972 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000973 if (CurrentToken->is(tok::comma))
974 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000975 if (!consumeToken())
976 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000977 }
978 return false;
979 }
980
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000981 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000982 if (!CurrentToken)
983 return false;
984
985 // A '[' could be an index subscript (after an indentifier or after
986 // ')' or ']'), or it could be the start of an Objective-C method
987 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000988 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000989 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000990 !Left->Parent || Left->Parent->is(tok::colon) ||
991 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
992 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
993 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000994 true, true) > prec::Unknown;
995
Nico Weber250fe712013-01-18 02:43:57 +0000996 ObjCSelectorRAII objCSelector(*this);
997 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000998 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000999
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001000 while (CurrentToken != NULL) {
1001 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +00001002 if (!CurrentToken->Children.empty() &&
1003 CurrentToken->Children[0].is(tok::l_paren)) {
1004 // An ObjC method call can't be followed by an open parenthesis.
1005 // FIXME: Do we incorrectly label ":" with this?
1006 StartsObjCMethodExpr = false;
1007 Left->Type = TT_Unknown;
1008 }
Nico Weber250fe712013-01-18 02:43:57 +00001009 if (StartsObjCMethodExpr)
1010 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001011 Left->MatchingParen = CurrentToken;
1012 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001013 next();
1014 return true;
1015 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001016 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001018 if (CurrentToken->is(tok::comma))
1019 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001020 if (!consumeToken())
1021 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001022 }
1023 return false;
1024 }
1025
Daniel Jasper83a54d22013-01-10 09:26:47 +00001026 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001027 // Lines are fine to end with '{'.
1028 if (CurrentToken == NULL)
1029 return true;
1030 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001031 while (CurrentToken != NULL) {
1032 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001033 Left->MatchingParen = CurrentToken;
1034 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001035 next();
1036 return true;
1037 }
1038 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1039 return false;
1040 if (!consumeToken())
1041 return false;
1042 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001043 return true;
1044 }
1045
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001046 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001047 while (CurrentToken != NULL) {
1048 if (CurrentToken->is(tok::colon)) {
1049 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001050 next();
1051 return true;
1052 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001053 if (!consumeToken())
1054 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001055 }
1056 return false;
1057 }
1058
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001059 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001060 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1061 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001062 next();
1063 if (!parseAngle())
1064 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001065 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001066 return true;
1067 }
1068 return false;
1069 }
1070
Daniel Jasperc0880a92013-01-04 18:52:56 +00001071 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001072 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001073 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001074 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001075 case tok::plus:
1076 case tok::minus:
1077 // At the start of the line, +/- specific ObjectiveC method
1078 // declarations.
1079 if (Tok->Parent == NULL)
1080 Tok->Type = TT_ObjCMethodSpecifier;
1081 break;
Nico Webera7252d82013-01-12 06:18:40 +00001082 case tok::colon:
1083 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001084 if (Tok->Parent->is(tok::r_paren))
1085 Tok->Type = TT_CtorInitializerColon;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001086 else if (ColonIsObjCMethodExpr)
Nico Webera7252d82013-01-12 06:18:40 +00001087 Tok->Type = TT_ObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001088 else if (ColonIsForRangeExpr)
1089 Tok->Type = TT_RangeBasedForLoopColon;
Nico Webera7252d82013-01-12 06:18:40 +00001090 break;
Nico Weber80a82762013-01-17 17:17:19 +00001091 case tok::kw_if:
1092 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001093 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001094 next();
1095 if (!parseParens(/*LookForDecls=*/true))
1096 return false;
1097 }
1098 break;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001099 case tok::kw_for:
1100 ColonIsForRangeExpr = true;
1101 next();
1102 if (!parseParens())
1103 return false;
1104 break;
Nico Webera5510af2013-01-18 05:50:57 +00001105 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001106 if (!parseParens())
1107 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001108 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001109 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001110 if (!parseSquare())
1111 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001113 case tok::l_brace:
1114 if (!parseBrace())
1115 return false;
1116 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001117 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001118 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001119 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001120 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 Tok->Type = TT_BinaryOperator;
1122 CurrentToken = Tok;
1123 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001124 }
1125 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001126 case tok::r_paren:
1127 case tok::r_square:
1128 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001129 case tok::r_brace:
1130 // Lines can start with '}'.
1131 if (Tok->Parent != NULL)
1132 return false;
1133 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001134 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001136 break;
1137 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001138 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001139 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001140 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001141 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1142 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001143 next();
1144 }
1145 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001146 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1147 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001148 next();
1149 }
1150 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001151 break;
1152 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001153 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001154 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001155 case tok::kw_template:
1156 parseTemplateDeclaration();
1157 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001158 default:
1159 break;
1160 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001161 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001162 }
1163
Daniel Jasper050948a52012-12-21 17:58:39 +00001164 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001165 next();
1166 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1167 next();
1168 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001169 if (CurrentToken->isNot(tok::comment) ||
1170 !CurrentToken->Children.empty())
1171 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001172 next();
1173 }
1174 } else {
1175 while (CurrentToken != NULL) {
1176 next();
1177 }
1178 }
1179 }
1180
1181 void parseWarningOrError() {
1182 next();
1183 // We still want to format the whitespace left of the first token of the
1184 // warning or error.
1185 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001186 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001187 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001188 next();
1189 }
1190 }
1191
1192 void parsePreprocessorDirective() {
1193 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001194 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001195 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001196 // Hashes in the middle of a line can lead to any strange token
1197 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001198 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001199 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001200 switch (
1201 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001202 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001203 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001204 parseIncludeDirective();
1205 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001206 case tok::pp_error:
1207 case tok::pp_warning:
1208 parseWarningOrError();
1209 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001210 default:
1211 break;
1212 }
1213 }
1214
Daniel Jasperda16db32013-01-07 10:48:50 +00001215 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001216 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001217 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001218 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001219 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001220 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001221 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001222 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001223
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001224 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001225 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001226 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1227 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001228 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1229 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1230 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001231 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001232 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001233 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001234 if (KeywordVirtualFound)
1235 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001236
1237 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001238 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001239 return LT_BuilderTypeCall;
1240
Daniel Jasperda16db32013-01-07 10:48:50 +00001241 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001242 }
1243
1244 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001245 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1246 CurrentToken = &CurrentToken->Children[0];
1247 else
1248 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001249 }
1250
1251 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001252 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001253 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001254 bool ColonIsObjCMethodExpr;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001255 bool ColonIsForRangeExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001256 };
1257
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001258 void calculateExtraInformation(AnnotatedToken &Current) {
1259 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1260
Manuel Klimek52b15152013-01-09 15:25:02 +00001261 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001262 Current.MustBreakBefore = true;
1263 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001264 if (Current.Type == TT_LineComment) {
1265 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001266 } else if ((Current.Parent->is(tok::comment) &&
1267 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001268 (Current.is(tok::string_literal) &&
1269 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001270 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001271 } else {
1272 Current.MustBreakBefore = false;
1273 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001274 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001275 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001276 if (Current.MustBreakBefore)
1277 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1278 else
1279 Current.TotalLength = Current.Parent->TotalLength +
1280 Current.FormatTok.TokenLength +
1281 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001282 if (!Current.Children.empty())
1283 calculateExtraInformation(Current.Children[0]);
1284 }
1285
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001286 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001287 AnnotatingParser Parser(Line.First);
1288 Line.Type = Parser.parseLine();
1289 if (Line.Type == LT_Invalid)
1290 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001291
Daniel Jasper5b49f472013-01-23 12:10:53 +00001292 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001293
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001294 if (Line.First.Type == TT_ObjCMethodSpecifier)
1295 Line.Type = LT_ObjCMethodDecl;
1296 else if (Line.First.Type == TT_ObjCDecl)
1297 Line.Type = LT_ObjCDecl;
1298 else if (Line.First.Type == TT_ObjCProperty)
1299 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001300
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001301 Line.First.SpaceRequiredBefore = true;
1302 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1303 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001304
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001305 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001306 if (!Line.First.Children.empty())
1307 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001308 }
1309
1310private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001311 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1312 if (getPrecedence(Current) == prec::Assignment) {
1313 IsExpression = true;
1314 AnnotatedToken *Previous = Current.Parent;
1315 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001316 if (Previous->Type == TT_BinaryOperator &&
1317 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001318 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001319 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001320 Previous = Previous->Parent;
1321 }
1322 }
1323 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001324 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1325 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001326 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001327
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001328 if (Current.Type == TT_Unknown) {
1329 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001330 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001331 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1332 Current.is(tok::caret)) {
1333 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001334 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1335 Current.Type = determineIncrementUsage(Current);
1336 } else if (Current.is(tok::exclaim)) {
1337 Current.Type = TT_UnaryOperator;
1338 } else if (isBinaryOperator(Current)) {
1339 Current.Type = TT_BinaryOperator;
1340 } else if (Current.is(tok::comment)) {
1341 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1342 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001343 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001344 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001345 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001346 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001347 } else if (Current.is(tok::r_paren) &&
1348 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001349 Current.Parent->Type == TT_TemplateCloser) &&
1350 (Current.Children.empty() ||
1351 (Current.Children[0].isNot(tok::equal) &&
1352 Current.Children[0].isNot(tok::semi) &&
1353 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001354 // FIXME: We need to get smarter and understand more cases of casts.
1355 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001356 } else if (Current.is(tok::at) && Current.Children.size()) {
1357 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1358 case tok::objc_interface:
1359 case tok::objc_implementation:
1360 case tok::objc_protocol:
1361 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001362 break;
1363 case tok::objc_property:
1364 Current.Type = TT_ObjCProperty;
1365 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001366 default:
1367 break;
1368 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001369 }
1370 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001371
1372 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001373 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001374 }
1375
Daniel Jasper71945272013-01-15 14:27:39 +00001376 /// \brief Returns the previous token ignoring comments.
1377 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1378 const AnnotatedToken *PrevToken = Tok.Parent;
1379 while (PrevToken != NULL && PrevToken->is(tok::comment))
1380 PrevToken = PrevToken->Parent;
1381 return PrevToken;
1382 }
1383
1384 /// \brief Returns the next token ignoring comments.
1385 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1386 if (Tok.Children.empty())
1387 return NULL;
1388 const AnnotatedToken *NextToken = &Tok.Children[0];
1389 while (NextToken->is(tok::comment)) {
1390 if (NextToken->Children.empty())
1391 return NULL;
1392 NextToken = &NextToken->Children[0];
1393 }
1394 return NextToken;
1395 }
1396
1397 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001398 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1399 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001400 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1401 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001402 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001403
1404 const AnnotatedToken *NextToken = getNextToken(Tok);
1405 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001406 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001407
Daniel Jasper0b820602013-01-22 11:46:26 +00001408 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1409 return TT_PointerOrReference;
1410
Daniel Jasper71945272013-01-15 14:27:39 +00001411 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1412 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1413 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1414 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001415 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001416 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001417
Daniel Jasper71945272013-01-15 14:27:39 +00001418 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1419 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1420 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1421 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1422 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1423 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1424 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001425 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001426
Daniel Jasper71945272013-01-15 14:27:39 +00001427 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1428 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001429 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001430
Daniel Jasper426702d2012-12-05 07:51:39 +00001431 // It is very unlikely that we are going to find a pointer or reference type
1432 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001433 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001434 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001435
Daniel Jasperda16db32013-01-07 10:48:50 +00001436 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001437 }
1438
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001439 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001440 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1441 if (PrevToken == NULL)
1442 return TT_UnaryOperator;
1443
Daniel Jasper8dd40472012-12-21 09:41:31 +00001444 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001445 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1446 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1447 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1448 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1449 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001450 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001451
1452 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001453 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001454 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001455
1456 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001457 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001458 }
1459
1460 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001461 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001462 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1463 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001464 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001465 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1466 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001467 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001468
Daniel Jasperda16db32013-01-07 10:48:50 +00001469 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001470 }
1471
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001472 bool spaceRequiredBetween(const AnnotatedToken &Left,
1473 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001474 if (Right.is(tok::hashhash))
1475 return Left.is(tok::hash);
1476 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1477 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001478 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1479 return false;
Nico Webera6087752013-01-10 20:12:55 +00001480 if (Right.is(tok::less) &&
1481 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001482 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001483 return true;
1484 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1485 return false;
1486 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1487 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001488 if (Left.is(tok::at) &&
1489 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1490 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001491 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1492 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001493 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001494 if (Left.is(tok::coloncolon))
1495 return false;
1496 if (Right.is(tok::coloncolon))
1497 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001498 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1499 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001500 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001501 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001502 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1503 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001504 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001505 return Right.FormatTok.Tok.isLiteral() ||
1506 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001507 if (Right.is(tok::star) && Left.is(tok::l_paren))
1508 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001509 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1510 return false;
1511 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001512 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001513 if (Left.is(tok::period) || Right.is(tok::period))
1514 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001515 if (Left.is(tok::colon))
1516 return Left.Type != TT_ObjCMethodExpr;
1517 if (Right.is(tok::colon))
1518 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001519 if (Left.is(tok::l_paren))
1520 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001521 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001522 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001523 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001524 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001525 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1526 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001527 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001528 if (Left.is(tok::at) &&
1529 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001530 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001531 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1532 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 return true;
1534 }
1535
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001536 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001537 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001538 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1539 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001540 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001541 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001542 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001543 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001544 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001545 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001546 // Don't space between ')' and <id>
1547 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001548 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001549 // Don't space between ':' and '('
1550 return false;
1551 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001553 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1554 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001555
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001556 if (Tok.Parent->is(tok::comma))
1557 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001558 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001559 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001560 if (Tok.Type == TT_OverloadedOperator)
1561 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001562 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001563 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001564 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001565 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001566 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001567 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001568 if (Tok.Parent->Type == TT_UnaryOperator ||
1569 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001570 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001571 if (Tok.Type == TT_UnaryOperator)
1572 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001573 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1574 (Tok.Parent->isNot(tok::colon) ||
1575 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001576 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1577 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001578 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1579 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001580 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001581 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001582 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001583 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001584 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001585 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001586 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001587 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001588 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001589 }
1590
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001591 bool canBreakBefore(const AnnotatedToken &Right) {
1592 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001593 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001594 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1595 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001596 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001597 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1598 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001599 // Don't break this identifier as ':' or identifier
1600 // before it will break.
1601 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001602 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1603 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001604 // Don't break at ':' if identifier before it can beak.
1605 return false;
1606 }
Nico Webera7252d82013-01-12 06:18:40 +00001607 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1608 return false;
1609 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1610 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001611 if (isObjCSelectorName(Right))
1612 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001613 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001614 return true;
Daniel Jasperca6623b2013-01-28 12:45:14 +00001615 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1616 return true;
Daniel Jasper0b41cbb2013-01-28 13:21:16 +00001617 if (Left.Type == TT_RangeBasedForLoopColon)
1618 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001619 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperca6623b2013-01-28 12:45:14 +00001620 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1621 Left.is(tok::question))
Daniel Jasperd1926a32013-01-02 08:44:14 +00001622 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001623 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001624 return false;
1625
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001626 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001627 // We rely on MustBreakBefore being set correctly here as we should not
1628 // change the "binding" behavior of a comment.
1629 return false;
1630
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001631 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1632 // unless it is follow by ';', '{' or '='.
1633 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1634 Left.Parent->is(tok::r_paren))
1635 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1636 Right.isNot(tok::equal);
1637
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001638 // We only break before r_brace if there was a corresponding break before
1639 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1640 if (Right.is(tok::r_brace))
1641 return false;
1642
Daniel Jasper71945272013-01-15 14:27:39 +00001643 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001644 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001645 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1646 Left.is(tok::comma) || Right.is(tok::lessless) ||
1647 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001648 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1649 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001650 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1651 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001652 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1653 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001654 }
1655
Daniel Jasperf7935112012-12-03 18:12:45 +00001656 FormatStyle Style;
1657 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001658 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001659 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001660};
1661
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001662class LexerBasedFormatTokenSource : public FormatTokenSource {
1663public:
1664 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001665 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001666 IdentTable(Lex.getLangOpts()) {
1667 Lex.SetKeepWhitespaceMode(true);
1668 }
1669
1670 virtual FormatToken getNextToken() {
1671 if (GreaterStashed) {
1672 FormatTok.NewlinesBefore = 0;
1673 FormatTok.WhiteSpaceStart =
1674 FormatTok.Tok.getLocation().getLocWithOffset(1);
1675 FormatTok.WhiteSpaceLength = 0;
1676 GreaterStashed = false;
1677 return FormatTok;
1678 }
1679
1680 FormatTok = FormatToken();
1681 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001682 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001683 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001684 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1685 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001686
1687 // Consume and record whitespace until we find a significant token.
1688 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001689 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001690 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1691 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001692 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1693
1694 if (FormatTok.Tok.is(tok::eof))
1695 return FormatTok;
1696 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001697 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001698 }
Manuel Klimekef920692013-01-07 07:56:50 +00001699
1700 // Now FormatTok is the next non-whitespace token.
1701 FormatTok.TokenLength = Text.size();
1702
Manuel Klimek1abf7892013-01-04 23:34:14 +00001703 // In case the token starts with escaped newlines, we want to
1704 // take them into account as whitespace - this pattern is quite frequent
1705 // in macro definitions.
1706 // FIXME: What do we want to do with other escaped spaces, and escaped
1707 // spaces or newlines in the middle of tokens?
1708 // FIXME: Add a more explicit test.
1709 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001710 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001711 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001712 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001713 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001714 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001715 }
1716
1717 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001718 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001719 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001720 FormatTok.Tok.setKind(Info.getTokenID());
1721 }
1722
1723 if (FormatTok.Tok.is(tok::greatergreater)) {
1724 FormatTok.Tok.setKind(tok::greater);
1725 GreaterStashed = true;
1726 }
1727
1728 return FormatTok;
1729 }
1730
1731private:
1732 FormatToken FormatTok;
1733 bool GreaterStashed;
1734 Lexer &Lex;
1735 SourceManager &SourceMgr;
1736 IdentifierTable IdentTable;
1737
1738 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001739 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001740 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1741 Tok.getLength());
1742 }
1743};
1744
Daniel Jasperf7935112012-12-03 18:12:45 +00001745class Formatter : public UnwrappedLineConsumer {
1746public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001747 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1748 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001749 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001750 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001751 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001752
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001753 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001754
Daniel Jasperf7935112012-12-03 18:12:45 +00001755 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001756 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001757 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001758 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001759 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001760 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1761 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1762 Annotator.annotate();
1763 }
1764 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1765 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001766 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001767 const AnnotatedLine &TheLine = *I;
1768 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1769 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1770 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001771 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001772 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001773 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001774 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001775 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001776 PreviousEndOfLineColumn = Formatter.format();
1777 } else {
1778 // If we did not reformat this unwrapped line, the column at the end of
1779 // the last token is unchanged - thus, we can calculate the end of the
1780 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001781 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001782 SourceMgr.getSpellingColumnNumber(
1783 TheLine.Last->FormatTok.Tok.getLocation()) +
1784 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1785 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001786 1;
1787 }
1788 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001789 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001790 }
1791
1792private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001793 /// \brief Tries to merge lines into one.
1794 ///
1795 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1796 /// if possible; note that \c I will be incremented when lines are merged.
1797 ///
1798 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001799 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001800 std::vector<AnnotatedLine>::iterator &I,
1801 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001802 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1803
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001804 // We can never merge stuff if there are trailing line comments.
1805 if (I->Last->Type == TT_LineComment)
1806 return;
1807
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001808 // Check whether the UnwrappedLine can be put onto a single line. If
1809 // so, this is bound to be the optimal solution (by definition) and we
1810 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001811 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001812 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001813 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001814
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001815 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001816 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001817
Daniel Jasper25837aa2013-01-14 14:14:23 +00001818 if (I->Last->is(tok::l_brace)) {
1819 tryMergeSimpleBlock(I, E, Limit);
1820 } else if (I->First.is(tok::kw_if)) {
1821 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001822 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1823 I->First.FormatTok.IsFirst)) {
1824 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001825 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001826 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001827 }
1828
Daniel Jasper39825ea2013-01-14 15:40:57 +00001829 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1830 std::vector<AnnotatedLine>::iterator E,
1831 unsigned Limit) {
1832 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001833 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1834 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001835 if (I + 2 != E && (I + 2)->InPPDirective &&
1836 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1837 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001838 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001839 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001840 join(Line, *(++I));
1841 }
1842
Daniel Jasper25837aa2013-01-14 14:14:23 +00001843 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1844 std::vector<AnnotatedLine>::iterator E,
1845 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001846 if (!Style.AllowShortIfStatementsOnASingleLine)
1847 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001848 if ((I + 1)->InPPDirective != I->InPPDirective ||
1849 ((I + 1)->InPPDirective &&
1850 (I + 1)->First.FormatTok.HasUnescapedNewline))
1851 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001852 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001853 if (Line.Last->isNot(tok::r_paren))
1854 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001855 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001856 return;
1857 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1858 return;
1859 // Only inline simple if's (no nested if or else).
1860 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1861 return;
1862 join(Line, *(++I));
1863 }
1864
1865 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1866 std::vector<AnnotatedLine>::iterator E,
1867 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001868 // First, check that the current line allows merging. This is the case if
1869 // we're not in a control flow statement and the last token is an opening
1870 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001871 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001872 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001873 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1874 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1875 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1876 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001877 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001878 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1879 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001880 if (!AllowedTokens)
1881 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001882
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001883 AnnotatedToken *Tok = &(I + 1)->First;
1884 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1885 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1886 Tok->SpaceRequiredBefore = false;
1887 join(Line, *(I + 1));
1888 I += 1;
1889 } else {
1890 // Check that we still have three lines and they fit into the limit.
1891 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1892 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001893 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001894
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001895 // Second, check that the next line does not contain any braces - if it
1896 // does, readability declines when putting it into a single line.
1897 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1898 return;
1899 do {
1900 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1901 return;
1902 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1903 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001904
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001905 // Last, check that the third line contains a single closing brace.
1906 Tok = &(I + 2)->First;
1907 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1908 Tok->MustBreakBefore)
1909 return;
1910
1911 join(Line, *(I + 1));
1912 join(Line, *(I + 2));
1913 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001914 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001915 }
1916
1917 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1918 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001919 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1920 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001921 }
1922
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001923 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1924 A.Last->Children.push_back(B.First);
1925 while (!A.Last->Children.empty()) {
1926 A.Last->Children[0].Parent = A.Last;
1927 A.Last = &A.Last->Children[0];
1928 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001929 }
1930
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001931 bool touchesRanges(const AnnotatedLine &TheLine) {
1932 const FormatToken *First = &TheLine.First.FormatTok;
1933 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001934 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001935 First->Tok.getLocation(),
1936 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001937 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001938 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1939 Ranges[i].getBegin()) &&
1940 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1941 LineRange.getBegin()))
1942 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001943 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001944 return false;
1945 }
1946
1947 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001948 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001949 }
1950
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001951 /// \brief Add a new line and the required indent before the first Token
1952 /// of the \c UnwrappedLine if there was no structural parsing error.
1953 /// Returns the indent level of the \c UnwrappedLine.
1954 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1955 bool InPPDirective,
1956 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001957 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001958 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1959 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1960
1961 unsigned Newlines = std::min(Tok.NewlinesBefore,
1962 Style.MaxEmptyLinesToKeep + 1);
1963 if (Newlines == 0 && !Tok.IsFirst)
1964 Newlines = 1;
1965 unsigned Indent = Level * 2;
1966
1967 bool IsAccessModifier = false;
1968 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1969 RootToken.is(tok::kw_private))
1970 IsAccessModifier = true;
1971 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1972 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1973 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1974 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1975 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1976 IsAccessModifier = true;
1977
1978 if (IsAccessModifier &&
1979 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1980 Indent += Style.AccessModifierOffset;
1981 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001982 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001983 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001984 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1985 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001986 }
1987 return Indent;
1988 }
1989
Alexander Kornienko116ba682013-01-14 11:34:14 +00001990 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001991 FormatStyle Style;
1992 Lexer &Lex;
1993 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001994 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001995 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001996 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001997 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001998};
1999
2000tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
2001 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002002 std::vector<CharSourceRange> Ranges,
2003 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002004 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00002005 OwningPtr<DiagnosticConsumer> DiagPrinter;
2006 if (DiagClient == 0) {
2007 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
2008 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
2009 DiagClient = DiagPrinter.get();
2010 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002011 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002012 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00002013 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00002014 Diagnostics.setSourceManager(&SourceMgr);
2015 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00002016 return formatter.format();
2017}
2018
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002019LangOptions getFormattingLangOpts() {
2020 LangOptions LangOpts;
2021 LangOpts.CPlusPlus = 1;
2022 LangOpts.CPlusPlus11 = 1;
2023 LangOpts.Bool = 1;
2024 LangOpts.ObjC1 = 1;
2025 LangOpts.ObjC2 = 1;
2026 return LangOpts;
2027}
2028
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002029} // namespace format
2030} // namespace clang