blob: 089035a35604f34afce65aa1dfdfb12800b2acd4 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000063 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000064 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000069};
70
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000073 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL),
77 ParameterCount(1), Parent(NULL) {
78 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000079
Daniel Jasper25837aa2013-01-14 14:14:23 +000080 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
81 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
82
Daniel Jasper7c85fde2013-01-08 14:56:18 +000083 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
84 return FormatTok.Tok.isObjCAtKeyword(Kind);
85 }
86
87 FormatToken FormatTok;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 TokenType Type;
90
Daniel Jasperf7935112012-12-03 18:12:45 +000091 bool SpaceRequiredBefore;
92 bool CanBreakBefore;
93 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000094
95 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000096
Daniel Jasper9278eb92013-01-16 14:59:02 +000097 AnnotatedToken *MatchingParen;
98
Daniel Jasper7b5773e92013-01-28 07:35:34 +000099 /// \brief Number of parameters, if this is "(", "[" or "<".
100 ///
101 /// This is initialized to 1 as we don't need to distinguish functions with
102 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
103 /// the number of commas.
104 unsigned ParameterCount;
105
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000106 /// \brief The total length of the line up to and including this token.
107 unsigned TotalLength;
108
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000109 std::vector<AnnotatedToken> Children;
110 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000111
112 const AnnotatedToken *getPreviousNoneComment() const {
113 AnnotatedToken *Tok = Parent;
114 while (Tok != NULL && Tok->is(tok::comment))
115 Tok = Tok->Parent;
116 return Tok;
117 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000118};
119
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000120class AnnotatedLine {
121public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000122 AnnotatedLine(const UnwrappedLine &Line)
123 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000124 InPPDirective(Line.InPPDirective),
125 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000126 assert(!Line.Tokens.empty());
127 AnnotatedToken *Current = &First;
128 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
129 E = Line.Tokens.end();
130 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000132 Current->Children[0].Parent = Current;
133 Current = &Current->Children[0];
134 }
135 Last = Current;
136 }
137 AnnotatedLine(const AnnotatedLine &Other)
138 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000139 InPPDirective(Other.InPPDirective),
140 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000141 Last = &First;
142 while (!Last->Children.empty()) {
143 Last->Children[0].Parent = Last;
144 Last = &Last->Children[0];
145 }
146 }
147
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000148 AnnotatedToken First;
149 AnnotatedToken *Last;
150
151 LineType Type;
152 unsigned Level;
153 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000154 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000155};
156
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000157static prec::Level getPrecedence(const AnnotatedToken &Tok) {
158 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000159}
160
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000161bool isBinaryOperator(const AnnotatedToken &Tok) {
162 // Comma is a binary operator, but does not behave as such wrt. formatting.
163 return getPrecedence(Tok) > prec::Comma;
164}
165
Daniel Jasperf7935112012-12-03 18:12:45 +0000166FormatStyle getLLVMStyle() {
167 FormatStyle LLVMStyle;
168 LLVMStyle.ColumnLimit = 80;
169 LLVMStyle.MaxEmptyLinesToKeep = 1;
170 LLVMStyle.PointerAndReferenceBindToType = false;
171 LLVMStyle.AccessModifierOffset = -2;
172 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000173 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000174 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000175 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000176 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000177 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000178 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000179 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000180 return LLVMStyle;
181}
182
183FormatStyle getGoogleStyle() {
184 FormatStyle GoogleStyle;
185 GoogleStyle.ColumnLimit = 80;
186 GoogleStyle.MaxEmptyLinesToKeep = 1;
187 GoogleStyle.PointerAndReferenceBindToType = true;
188 GoogleStyle.AccessModifierOffset = -1;
189 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000190 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000191 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000192 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000193 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000194 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000195 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000196 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000197 return GoogleStyle;
198}
199
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000200FormatStyle getChromiumStyle() {
201 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000202 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000203 return ChromiumStyle;
204}
205
Daniel Jasperf7935112012-12-03 18:12:45 +0000206struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000207 unsigned PenaltyIndentLevel;
Daniel Jasper2df93312013-01-09 10:16:05 +0000208 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000209};
210
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000211/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000212///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000213/// This includes special handling for certain constructs, e.g. the alignment of
214/// trailing line comments.
215class WhitespaceManager {
216public:
217 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
218
219 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
220 /// each \c AnnotatedToken.
221 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
222 unsigned Spaces, unsigned WhitespaceStartColumn,
223 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000224 // 2+ newlines mean an empty line separating logic scopes.
225 if (NewLines >= 2)
226 alignComments();
227
228 // Align line comments if they are trailing or if they continue other
229 // trailing comments.
230 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000231 (Tok.Parent != NULL || !Comments.empty())) {
232 if (Style.ColumnLimit >=
233 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
234 Comments.push_back(StoredComment());
235 Comments.back().Tok = Tok.FormatTok;
236 Comments.back().Spaces = Spaces;
237 Comments.back().NewLines = NewLines;
238 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
239 Comments.back().MaxColumn = Style.ColumnLimit -
240 Spaces - Tok.FormatTok.TokenLength;
241 return;
242 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000243 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000244
245 // If this line does not have a trailing comment, align the stored comments.
246 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
247 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000248 storeReplacement(Tok.FormatTok,
249 std::string(NewLines, '\n') + std::string(Spaces, ' '));
250 }
251
252 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
253 /// backslashes to escape newlines inside a preprocessor directive.
254 ///
255 /// This function and \c replaceWhitespace have the same behavior if
256 /// \c Newlines == 0.
257 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
258 unsigned Spaces, unsigned WhitespaceStartColumn,
259 const FormatStyle &Style) {
260 std::string NewLineText;
261 if (NewLines > 0) {
262 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
263 WhitespaceStartColumn);
264 for (unsigned i = 0; i < NewLines; ++i) {
265 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
266 NewLineText += "\\\n";
267 Offset = 0;
268 }
269 }
270 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
271 }
272
273 /// \brief Returns all the \c Replacements created during formatting.
274 const tooling::Replacements &generateReplacements() {
275 alignComments();
276 return Replaces;
277 }
278
279private:
280 /// \brief Structure to store a comment for later layout and alignment.
281 struct StoredComment {
282 FormatToken Tok;
283 unsigned MinColumn;
284 unsigned MaxColumn;
285 unsigned NewLines;
286 unsigned Spaces;
287 };
288 SmallVector<StoredComment, 16> Comments;
289 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
290
291 /// \brief Try to align all stashed comments.
292 void alignComments() {
293 unsigned MinColumn = 0;
294 unsigned MaxColumn = UINT_MAX;
295 comment_iterator Start = Comments.begin();
296 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
297 ++I) {
298 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
299 alignComments(Start, I, MinColumn);
300 MinColumn = I->MinColumn;
301 MaxColumn = I->MaxColumn;
302 Start = I;
303 } else {
304 MinColumn = std::max(MinColumn, I->MinColumn);
305 MaxColumn = std::min(MaxColumn, I->MaxColumn);
306 }
307 }
308 alignComments(Start, Comments.end(), MinColumn);
309 Comments.clear();
310 }
311
312 /// \brief Put all the comments between \p I and \p E into \p Column.
313 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
314 while (I != E) {
315 unsigned Spaces = I->Spaces + Column - I->MinColumn;
316 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
317 std::string(Spaces, ' '));
318 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000319 }
320 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000321
322 /// \brief Stores \p Text as the replacement for the whitespace in front of
323 /// \p Tok.
324 void storeReplacement(const FormatToken &Tok, const std::string Text) {
325 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
326 Tok.WhiteSpaceLength, Text));
327 }
328
329 SourceManager &SourceMgr;
330 tooling::Replacements Replaces;
331};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000332
Nico Weberc9d73612013-01-12 22:48:47 +0000333/// \brief Returns if a token is an Objective-C selector name.
334///
Nico Weber92c05392013-01-12 22:51:13 +0000335/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000336static bool isObjCSelectorName(const AnnotatedToken &Tok) {
337 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
338 Tok.Children[0].is(tok::colon) &&
339 Tok.Children[0].Type == TT_ObjCMethodExpr;
340}
341
Daniel Jasperf7935112012-12-03 18:12:45 +0000342class UnwrappedLineFormatter {
343public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000344 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000345 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000346 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000347 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000348 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000349 FirstIndent(FirstIndent), RootToken(RootToken),
350 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000351 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper2df93312013-01-09 10:16:05 +0000352 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000353 }
354
Manuel Klimek1abf7892013-01-04 23:34:14 +0000355 /// \brief Formats an \c UnwrappedLine.
356 ///
357 /// \returns The column after the last token in the last line of the
358 /// \c UnwrappedLine.
359 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000360 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000361 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000362 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000363 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000364 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000365 State.ForLoopVariablePos = 0;
366 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000367
Manuel Klimek24998102013-01-16 14:55:28 +0000368 DEBUG({
369 DebugTokenState(*State.NextToken);
370 });
371
Daniel Jaspere9de2602012-12-06 09:56:08 +0000372 // The first token has already been indented and thus consumed.
373 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000374
375 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000376 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000377 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
378 // Calculating the column is important for aligning trailing comments.
379 // FIXME: This does not seem to happen in conjunction with escaped
380 // newlines. If it does, fix!
381 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
382 State.NextToken->FormatTok.TokenLength;
383 State.NextToken = State.NextToken->Children.empty() ? NULL :
384 &State.NextToken->Children[0];
385 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000386 addTokenToState(false, false, State);
387 } else {
388 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
389 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000390 DEBUG({
391 if (Break < NoBreak)
392 llvm::errs() << "\n";
393 else
394 llvm::errs() << " ";
395 llvm::errs() << "<";
396 DebugPenalty(Break, Break < NoBreak);
397 llvm::errs() << "/";
398 DebugPenalty(NoBreak, !(Break < NoBreak));
399 llvm::errs() << "> ";
400 DebugTokenState(*State.NextToken);
401 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000402 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000403 if (State.NextToken != NULL &&
404 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
405 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000406 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000407 State.Stack.back().BreakAfterComma = true;
408 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000409 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000410 }
Manuel Klimek24998102013-01-16 14:55:28 +0000411 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000412 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000413 }
414
415private:
Manuel Klimek24998102013-01-16 14:55:28 +0000416 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
417 const Token &Tok = AnnotatedTok.FormatTok.Tok;
418 llvm::errs()
419 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
420 Tok.getLength());
421 llvm::errs();
422 }
423
424 void DebugPenalty(unsigned Penalty, bool Winner) {
425 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
426 if (Penalty == UINT_MAX)
427 llvm::errs() << "MAX";
428 else
429 llvm::errs() << Penalty;
430 llvm::errs().resetColor();
431 }
432
Daniel Jasper337816e2013-01-11 10:22:12 +0000433 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000434 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000435 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
436 FirstLessLess(0), BreakBeforeClosingBrace(false),
437 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000438
Daniel Jasperf7935112012-12-03 18:12:45 +0000439 /// \brief The position to which a specific parenthesis level needs to be
440 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000441 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000442
Daniel Jaspere9de2602012-12-06 09:56:08 +0000443 /// \brief The position of the last space on each level.
444 ///
445 /// Used e.g. to break like:
446 /// functionCall(Parameter, otherCall(
447 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000448 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000449
Daniel Jaspera836b902013-01-23 16:58:21 +0000450 /// \brief This is the column of the first token after an assignment.
451 unsigned AssignmentColumn;
452
Daniel Jaspere9de2602012-12-06 09:56:08 +0000453 /// \brief The position the first "<<" operator encountered on each level.
454 ///
455 /// Used to align "<<" operators. 0 if no such operator has been encountered
456 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000457 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000458
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000459 /// \brief Whether a newline needs to be inserted before the block's closing
460 /// brace.
461 ///
462 /// We only want to insert a newline before the closing brace if there also
463 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000464 bool BreakBeforeClosingBrace;
465
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000466 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000467 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000468
Daniel Jasper337816e2013-01-11 10:22:12 +0000469 bool operator<(const ParenState &Other) const {
470 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000471 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000472 if (LastSpace != Other.LastSpace)
473 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000474 if (AssignmentColumn != Other.AssignmentColumn)
475 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000476 if (FirstLessLess != Other.FirstLessLess)
477 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000478 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
479 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000480 if (BreakAfterComma != Other.BreakAfterComma)
481 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000482 if (HasMultiParameterLine != Other.HasMultiParameterLine)
483 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000484 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000485 }
486 };
487
488 /// \brief The current state when indenting a unwrapped line.
489 ///
490 /// As the indenting tries different combinations this is copied by value.
491 struct LineState {
492 /// \brief The number of used columns in the current line.
493 unsigned Column;
494
495 /// \brief The token that needs to be next formatted.
496 const AnnotatedToken *NextToken;
497
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000498 /// \brief The column of the first variable in a for-loop declaration.
499 ///
500 /// Used to align the second variable if necessary.
501 unsigned ForLoopVariablePos;
502
503 /// \brief \c true if this line contains a continued for-loop section.
504 bool LineContainsContinuedForLoopSection;
505
Daniel Jasper337816e2013-01-11 10:22:12 +0000506 /// \brief A stack keeping track of properties applying to parenthesis
507 /// levels.
508 std::vector<ParenState> Stack;
509
510 /// \brief Comparison operator to be able to used \c LineState in \c map.
511 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000512 if (Other.NextToken != NextToken)
513 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000514 if (Other.Column != Column)
515 return Other.Column > Column;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000516 if (Other.ForLoopVariablePos != ForLoopVariablePos)
517 return Other.ForLoopVariablePos < ForLoopVariablePos;
518 if (Other.LineContainsContinuedForLoopSection !=
519 LineContainsContinuedForLoopSection)
520 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000521 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000522 }
523 };
524
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000525 /// \brief Appends the next token to \p State and updates information
526 /// necessary for indentation.
527 ///
528 /// Puts the token on the current line if \p Newline is \c true and adds a
529 /// line break and necessary indentation otherwise.
530 ///
531 /// If \p DryRun is \c false, also creates and stores the required
532 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000533 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000534 const AnnotatedToken &Current = *State.NextToken;
535 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000536 assert(State.Stack.size());
537 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000538
539 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000540 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000541 if (Current.is(tok::r_brace)) {
542 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000543 } else if (Current.is(tok::string_literal) &&
544 Previous.is(tok::string_literal)) {
545 State.Column = State.Column - Previous.FormatTok.TokenLength;
546 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000547 State.Stack[ParenLevel].FirstLessLess != 0) {
548 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000549 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000550 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
551 Previous.is(tok::question) ||
552 Previous.Type == TT_ConditionalExpr ||
553 Current.is(tok::period) || Current.is(tok::arrow))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000554 // Indent and extra 4 spaces after if we know the current expression is
555 // continued. Don't do that on the top level, as we already indent 4
556 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000557 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000558 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000559 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000560 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000561 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000562 } else if (Previous.Type == TT_BinaryOperator &&
563 State.Stack.back().AssignmentColumn != 0) {
564 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000565 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000566 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000567 }
568
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000569 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000570 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000572 if (!DryRun) {
573 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000574 Whitespaces.replaceWhitespace(Current, 1, State.Column,
575 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000576 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000577 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
578 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000579 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000580
Daniel Jasper337816e2013-01-11 10:22:12 +0000581 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000582 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000583 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000584 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000585 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
586 State.ForLoopVariablePos = State.Column -
587 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000588
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000589 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
590 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000591 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000592
Daniel Jasperf7935112012-12-03 18:12:45 +0000593 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000594 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000595
Daniel Jasperbcab4302013-01-09 10:40:23 +0000596 // FIXME: Do we need to do this for assignments nested in other
597 // expressions?
598 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000599 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000600 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000601 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000602 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000603 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000604 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000605 if (Current.getPreviousNoneComment() != NULL &&
606 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000607 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000608 State.Stack[ParenLevel].HasMultiParameterLine = true;
609
Daniel Jaspere9de2602012-12-06 09:56:08 +0000610 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000611 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
612 // Treat the condition inside an if as if it was a second function
613 // parameter, i.e. let nested calls have an indent of 4.
614 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000615 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000616 // Top-level spaces are exempt as that mostly leads to better results.
617 State.Stack.back().LastSpace = State.Column;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000618 else if (Previous.Type == TT_BinaryOperator &&
619 getPrecedence(Previous) != prec::Assignment)
620 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000621 else if (Previous.ParameterCount > 1 &&
622 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
623 Previous.Type == TT_TemplateOpener))
624 // If this function has multiple parameters, indent nested calls from
625 // the start of the first parameter.
626 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000627 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000628
629 // If we break after an {, we should also break before the corresponding }.
630 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000631 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000632
Daniel Jaspere941b162013-01-23 10:08:28 +0000633 if (!Style.BinPackParameters && Newline) {
634 // If we are breaking after '(', '{', '<', this is not bin packing unless
635 // AllowAllParametersOnNextLine is false.
636 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
637 Previous.Type != TT_TemplateOpener) ||
638 !Style.AllowAllParametersOnNextLine)
639 State.Stack.back().BreakAfterComma = true;
640
641 // Any break on this level means that the parent level has been broken
642 // and we need to avoid bin packing there.
643 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
644 State.Stack[i].BreakAfterComma = true;
645 }
646 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000647
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000648 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000649 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000650
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000651 /// \brief Mark the next token as consumed in \p State and modify its stacks
652 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000653 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000654 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000655 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000656
Daniel Jasper337816e2013-01-11 10:22:12 +0000657 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
658 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000659
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000660 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000661 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000662 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
663 Current.is(tok::l_brace) ||
664 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000665 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000666 if (Current.is(tok::l_brace)) {
667 // FIXME: This does not work with nested static initializers.
668 // Implement a better handling for static initializers and similar
669 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000670 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000671 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000672 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000673 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000674 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000675 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000676 }
677
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000678 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000679 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
681 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
682 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000683 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000684 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000685
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000686 if (State.NextToken->Children.empty())
687 State.NextToken = NULL;
688 else
689 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000690
691 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000692 }
693
Nico Weber49cbc2c2013-01-07 15:15:29 +0000694 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000695 unsigned splitPenalty(const AnnotatedToken &Tok) {
696 const AnnotatedToken &Left = Tok;
697 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000698
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000699 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
700 return 50;
701 if (Left.is(tok::equal) && Right.is(tok::l_brace))
702 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000703 if (Left.is(tok::coloncolon))
704 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000705
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000706 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000707 if (RootToken.is(tok::kw_for) &&
708 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000709 return 20;
710
Daniel Jasper04468962013-01-18 10:56:38 +0000711 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000712 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000713
714 // In Objective-C method expressions, prefer breaking before "param:" over
715 // breaking after it.
716 if (isObjCSelectorName(Right))
717 return 0;
718 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
719 return 20;
720
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000721 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000722 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000723 // FIXME: The penalty for a trailing "<" or "[" being higher than the
724 // penalty for a trainling "(" is a temporary workaround until we can
725 // properly avoid breaking in array subscripts or template parameters.
726 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
727 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000728
Daniel Jasper399d24b2013-01-09 07:06:56 +0000729 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
730 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000731 prec::Level Level = getPrecedence(Left);
732
Daniel Jasperde5c2072012-12-24 00:13:23 +0000733 if (Level != prec::Unknown)
734 return Level;
735
Daniel Jasper04468962013-01-18 10:56:38 +0000736 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000737 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000738 return 5; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000739 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000740 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000741
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 return 3;
743 }
744
Daniel Jasper2df93312013-01-09 10:16:05 +0000745 unsigned getColumnLimit() {
746 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
747 }
748
Daniel Jasperf7935112012-12-03 18:12:45 +0000749 /// \brief Calculate the number of lines needed to format the remaining part
750 /// of the unwrapped line.
751 ///
752 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000753 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000754 /// added after the previous token.
755 ///
756 /// \param StopAt is used for optimization. If we can determine that we'll
757 /// definitely need at least \p StopAt additional lines, we already know of a
758 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000759 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000760 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000761 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000762 return 0;
763
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000766 if (NewLine && !State.NextToken->CanBreakBefore &&
767 !(State.NextToken->is(tok::r_brace) &&
768 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000769 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000770 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000771 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000772 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000773 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000774 State.LineContainsContinuedForLoopSection)
775 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000776 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000777 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000778 State.Stack.back().BreakAfterComma)
779 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000780 // Trying to insert a parameter on a new line if there are already more than
781 // one parameter on the current line is bin packing.
782 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
783 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
784 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000785 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
786 (State.NextToken->Parent->ClosesTemplateDeclaration &&
787 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000788 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000789
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000790 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000791 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000792 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000793 splitPenalty(*State.NextToken->Parent);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000794
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000795 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000796
Daniel Jasper2df93312013-01-09 10:16:05 +0000797 // Exceeding column limit is bad, assign penalty.
798 if (State.Column > getColumnLimit()) {
799 unsigned ExcessCharacters = State.Column - getColumnLimit();
800 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
801 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000802
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 if (StopAt <= CurrentPenalty)
804 return UINT_MAX;
805 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000806 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000807 if (I != Memory.end()) {
808 // If this state has already been examined, we can safely return the
809 // previous result if we
810 // - have not hit the optimatization (and thus returned UINT_MAX) OR
811 // - are now computing for a smaller or equal StopAt.
812 unsigned SavedResult = I->second.first;
813 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000814 if (SavedResult != UINT_MAX)
815 return SavedResult + CurrentPenalty;
816 else if (StopAt <= SavedStopAt)
817 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000818 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000819
820 unsigned NoBreak = calcPenalty(State, false, StopAt);
821 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
822 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000823
824 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
825 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000826 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000827
828 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000829 }
830
Daniel Jasperf7935112012-12-03 18:12:45 +0000831 FormatStyle Style;
832 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000833 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000834 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000835 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000836 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000837
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000838 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000839 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000840 StateMap Memory;
841
Daniel Jasperf7935112012-12-03 18:12:45 +0000842 OptimizationParameters Parameters;
843};
844
845/// \brief Determines extra information about the tokens comprising an
846/// \c UnwrappedLine.
847class TokenAnnotator {
848public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000849 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
850 AnnotatedLine &Line)
851 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000852
853 /// \brief A parser that gathers additional information about tokens.
854 ///
855 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
856 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
857 /// into template parameter lists.
858 class AnnotatingParser {
859 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000860 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000861 : CurrentToken(&RootToken), KeywordVirtualFound(false),
862 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000863
Nico Weber250fe712013-01-18 02:43:57 +0000864 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
865 struct ObjCSelectorRAII {
866 AnnotatingParser &P;
867 bool ColonWasObjCMethodExpr;
868
869 ObjCSelectorRAII(AnnotatingParser &P)
870 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
871
872 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
873
874 void markStart(AnnotatedToken &Left) {
875 P.ColonIsObjCMethodExpr = true;
876 Left.Type = TT_ObjCMethodExpr;
877 }
878
879 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
880 };
881
882
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000883 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000884 if (CurrentToken == NULL)
885 return false;
886 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000887 while (CurrentToken != NULL) {
888 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000889 Left->MatchingParen = CurrentToken;
890 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000891 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000892 next();
893 return true;
894 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000895 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
896 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000897 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000898 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
899 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000900 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000901 if (CurrentToken->is(tok::comma))
902 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000903 if (!consumeToken())
904 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000905 }
906 return false;
907 }
908
Nico Weber80a82762013-01-17 17:17:19 +0000909 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000910 if (CurrentToken == NULL)
911 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000912 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000913 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000914 if (CurrentToken->is(tok::caret)) {
915 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000916 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000917 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
918 // @selector( starts a selector.
919 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
920 MaybeSel->Parent->is(tok::at)) {
921 StartsObjCMethodExpr = true;
922 }
923 }
924
925 ObjCSelectorRAII objCSelector(*this);
926 if (StartsObjCMethodExpr)
927 objCSelector.markStart(*Left);
928
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000929 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000930 // LookForDecls is set when "if (" has been seen. Check for
931 // 'identifier' '*' 'identifier' followed by not '=' -- this
932 // '*' has to be a binary operator but determineStarAmpUsage() will
933 // categorize it as an unary operator, so set the right type here.
934 if (LookForDecls && !CurrentToken->Children.empty()) {
935 AnnotatedToken &Prev = *CurrentToken->Parent;
936 AnnotatedToken &Next = CurrentToken->Children[0];
937 if (Prev.Parent->is(tok::identifier) &&
938 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
939 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
940 Prev.Type = TT_BinaryOperator;
941 LookForDecls = false;
942 }
943 }
944
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000945 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000946 Left->MatchingParen = CurrentToken;
947 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000948
949 if (StartsObjCMethodExpr)
950 objCSelector.markEnd(*CurrentToken);
951
Daniel Jasperf7935112012-12-03 18:12:45 +0000952 next();
953 return true;
954 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000955 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000956 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000957 if (CurrentToken->is(tok::comma))
958 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000959 if (!consumeToken())
960 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 }
962 return false;
963 }
964
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000965 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000966 if (!CurrentToken)
967 return false;
968
969 // A '[' could be an index subscript (after an indentifier or after
970 // ')' or ']'), or it could be the start of an Objective-C method
971 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000972 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000973 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000974 !Left->Parent || Left->Parent->is(tok::colon) ||
975 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
976 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
977 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000978 true, true) > prec::Unknown;
979
Nico Weber250fe712013-01-18 02:43:57 +0000980 ObjCSelectorRAII objCSelector(*this);
981 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000982 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000983
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000984 while (CurrentToken != NULL) {
985 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000986 if (!CurrentToken->Children.empty() &&
987 CurrentToken->Children[0].is(tok::l_paren)) {
988 // An ObjC method call can't be followed by an open parenthesis.
989 // FIXME: Do we incorrectly label ":" with this?
990 StartsObjCMethodExpr = false;
991 Left->Type = TT_Unknown;
992 }
Nico Weber250fe712013-01-18 02:43:57 +0000993 if (StartsObjCMethodExpr)
994 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000995 Left->MatchingParen = CurrentToken;
996 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000997 next();
998 return true;
999 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001000 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001001 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001002 if (CurrentToken->is(tok::comma))
1003 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001004 if (!consumeToken())
1005 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006 }
1007 return false;
1008 }
1009
Daniel Jasper83a54d22013-01-10 09:26:47 +00001010 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001011 // Lines are fine to end with '{'.
1012 if (CurrentToken == NULL)
1013 return true;
1014 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001015 while (CurrentToken != NULL) {
1016 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001017 Left->MatchingParen = CurrentToken;
1018 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001019 next();
1020 return true;
1021 }
1022 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1023 return false;
1024 if (!consumeToken())
1025 return false;
1026 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001027 return true;
1028 }
1029
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001030 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 while (CurrentToken != NULL) {
1032 if (CurrentToken->is(tok::colon)) {
1033 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001034 next();
1035 return true;
1036 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001037 if (!consumeToken())
1038 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001039 }
1040 return false;
1041 }
1042
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001043 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001044 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1045 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001046 next();
1047 if (!parseAngle())
1048 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001049 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001050 return true;
1051 }
1052 return false;
1053 }
1054
Daniel Jasperc0880a92013-01-04 18:52:56 +00001055 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001056 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001057 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001058 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001059 case tok::plus:
1060 case tok::minus:
1061 // At the start of the line, +/- specific ObjectiveC method
1062 // declarations.
1063 if (Tok->Parent == NULL)
1064 Tok->Type = TT_ObjCMethodSpecifier;
1065 break;
Nico Webera7252d82013-01-12 06:18:40 +00001066 case tok::colon:
1067 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001068 if (Tok->Parent->is(tok::r_paren))
1069 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001070 if (ColonIsObjCMethodExpr)
1071 Tok->Type = TT_ObjCMethodExpr;
1072 break;
Nico Weber80a82762013-01-17 17:17:19 +00001073 case tok::kw_if:
1074 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001075 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001076 next();
1077 if (!parseParens(/*LookForDecls=*/true))
1078 return false;
1079 }
1080 break;
Nico Webera5510af2013-01-18 05:50:57 +00001081 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001082 if (!parseParens())
1083 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001084 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001085 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001086 if (!parseSquare())
1087 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001088 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001089 case tok::l_brace:
1090 if (!parseBrace())
1091 return false;
1092 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001094 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001095 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001096 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001097 Tok->Type = TT_BinaryOperator;
1098 CurrentToken = Tok;
1099 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 }
1101 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001102 case tok::r_paren:
1103 case tok::r_square:
1104 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001105 case tok::r_brace:
1106 // Lines can start with '}'.
1107 if (Tok->Parent != NULL)
1108 return false;
1109 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001110 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001111 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 break;
1113 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001114 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001115 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001116 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001117 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1118 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001119 next();
1120 }
1121 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001122 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1123 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001124 next();
1125 }
1126 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001127 break;
1128 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001129 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001130 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001131 case tok::kw_template:
1132 parseTemplateDeclaration();
1133 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001134 default:
1135 break;
1136 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001137 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001138 }
1139
Daniel Jasper050948a52012-12-21 17:58:39 +00001140 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001141 next();
1142 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1143 next();
1144 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001145 if (CurrentToken->isNot(tok::comment) ||
1146 !CurrentToken->Children.empty())
1147 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001148 next();
1149 }
1150 } else {
1151 while (CurrentToken != NULL) {
1152 next();
1153 }
1154 }
1155 }
1156
1157 void parseWarningOrError() {
1158 next();
1159 // We still want to format the whitespace left of the first token of the
1160 // warning or error.
1161 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001162 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001163 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001164 next();
1165 }
1166 }
1167
1168 void parsePreprocessorDirective() {
1169 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001170 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001171 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001172 // Hashes in the middle of a line can lead to any strange token
1173 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001174 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001175 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001176 switch (
1177 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001178 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001179 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001180 parseIncludeDirective();
1181 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001182 case tok::pp_error:
1183 case tok::pp_warning:
1184 parseWarningOrError();
1185 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001186 default:
1187 break;
1188 }
1189 }
1190
Daniel Jasperda16db32013-01-07 10:48:50 +00001191 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001192 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001193 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001194 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001195 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001196 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001197 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001198 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001199
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001200 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001201 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001202 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1203 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001204 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1205 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1206 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001207 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001208 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001209 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001210 if (KeywordVirtualFound)
1211 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001212
1213 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001214 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001215 return LT_BuilderTypeCall;
1216
Daniel Jasperda16db32013-01-07 10:48:50 +00001217 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001218 }
1219
1220 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1222 CurrentToken = &CurrentToken->Children[0];
1223 else
1224 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001225 }
1226
1227 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001228 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001229 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001230 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001231 };
1232
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001233 void calculateExtraInformation(AnnotatedToken &Current) {
1234 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1235
Manuel Klimek52b15152013-01-09 15:25:02 +00001236 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001237 Current.MustBreakBefore = true;
1238 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001239 if (Current.Type == TT_LineComment) {
1240 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001241 } else if ((Current.Parent->is(tok::comment) &&
1242 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001243 (Current.is(tok::string_literal) &&
1244 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001245 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001246 } else {
1247 Current.MustBreakBefore = false;
1248 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001249 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001250 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001251 if (Current.MustBreakBefore)
1252 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1253 else
1254 Current.TotalLength = Current.Parent->TotalLength +
1255 Current.FormatTok.TokenLength +
1256 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001257 if (!Current.Children.empty())
1258 calculateExtraInformation(Current.Children[0]);
1259 }
1260
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001261 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001262 AnnotatingParser Parser(Line.First);
1263 Line.Type = Parser.parseLine();
1264 if (Line.Type == LT_Invalid)
1265 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001266
Daniel Jasper5b49f472013-01-23 12:10:53 +00001267 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001268
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001269 if (Line.First.Type == TT_ObjCMethodSpecifier)
1270 Line.Type = LT_ObjCMethodDecl;
1271 else if (Line.First.Type == TT_ObjCDecl)
1272 Line.Type = LT_ObjCDecl;
1273 else if (Line.First.Type == TT_ObjCProperty)
1274 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001275
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001276 Line.First.SpaceRequiredBefore = true;
1277 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1278 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001279
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001280 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001281 if (!Line.First.Children.empty())
1282 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001283 }
1284
1285private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001286 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1287 if (getPrecedence(Current) == prec::Assignment) {
1288 IsExpression = true;
1289 AnnotatedToken *Previous = Current.Parent;
1290 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001291 if (Previous->Type == TT_BinaryOperator &&
1292 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001293 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001294 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001295 Previous = Previous->Parent;
1296 }
1297 }
1298 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001299 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1300 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001301 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001302
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001303 if (Current.Type == TT_Unknown) {
1304 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001305 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001306 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1307 Current.is(tok::caret)) {
1308 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001309 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1310 Current.Type = determineIncrementUsage(Current);
1311 } else if (Current.is(tok::exclaim)) {
1312 Current.Type = TT_UnaryOperator;
1313 } else if (isBinaryOperator(Current)) {
1314 Current.Type = TT_BinaryOperator;
1315 } else if (Current.is(tok::comment)) {
1316 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1317 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001318 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001319 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001320 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001321 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001322 } else if (Current.is(tok::r_paren) &&
1323 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001324 Current.Parent->Type == TT_TemplateCloser) &&
1325 (Current.Children.empty() ||
1326 (Current.Children[0].isNot(tok::equal) &&
1327 Current.Children[0].isNot(tok::semi) &&
1328 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001329 // FIXME: We need to get smarter and understand more cases of casts.
1330 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001331 } else if (Current.is(tok::at) && Current.Children.size()) {
1332 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1333 case tok::objc_interface:
1334 case tok::objc_implementation:
1335 case tok::objc_protocol:
1336 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001337 break;
1338 case tok::objc_property:
1339 Current.Type = TT_ObjCProperty;
1340 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001341 default:
1342 break;
1343 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001344 }
1345 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001346
1347 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001348 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001349 }
1350
Daniel Jasper71945272013-01-15 14:27:39 +00001351 /// \brief Returns the previous token ignoring comments.
1352 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1353 const AnnotatedToken *PrevToken = Tok.Parent;
1354 while (PrevToken != NULL && PrevToken->is(tok::comment))
1355 PrevToken = PrevToken->Parent;
1356 return PrevToken;
1357 }
1358
1359 /// \brief Returns the next token ignoring comments.
1360 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1361 if (Tok.Children.empty())
1362 return NULL;
1363 const AnnotatedToken *NextToken = &Tok.Children[0];
1364 while (NextToken->is(tok::comment)) {
1365 if (NextToken->Children.empty())
1366 return NULL;
1367 NextToken = &NextToken->Children[0];
1368 }
1369 return NextToken;
1370 }
1371
1372 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001373 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1374 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001375 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1376 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001377 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001378
1379 const AnnotatedToken *NextToken = getNextToken(Tok);
1380 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001381 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001382
Daniel Jasper0b820602013-01-22 11:46:26 +00001383 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1384 return TT_PointerOrReference;
1385
Daniel Jasper71945272013-01-15 14:27:39 +00001386 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1387 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1388 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1389 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001390 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001391 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001392
Daniel Jasper71945272013-01-15 14:27:39 +00001393 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1394 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1395 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1396 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1397 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1398 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1399 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001400 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001401
Daniel Jasper71945272013-01-15 14:27:39 +00001402 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1403 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001404 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001405
Daniel Jasper426702d2012-12-05 07:51:39 +00001406 // It is very unlikely that we are going to find a pointer or reference type
1407 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001408 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001409 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001410
Daniel Jasperda16db32013-01-07 10:48:50 +00001411 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001412 }
1413
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001414 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001415 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1416 if (PrevToken == NULL)
1417 return TT_UnaryOperator;
1418
Daniel Jasper8dd40472012-12-21 09:41:31 +00001419 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001420 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1421 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1422 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1423 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1424 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001425 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001426
1427 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001428 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001429 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001430
1431 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001432 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001433 }
1434
1435 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001436 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001437 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1438 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001439 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001440 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1441 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001442 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001443
Daniel Jasperda16db32013-01-07 10:48:50 +00001444 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001445 }
1446
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001447 bool spaceRequiredBetween(const AnnotatedToken &Left,
1448 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001449 if (Right.is(tok::hashhash))
1450 return Left.is(tok::hash);
1451 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1452 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001453 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1454 return false;
Nico Webera6087752013-01-10 20:12:55 +00001455 if (Right.is(tok::less) &&
1456 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001457 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001458 return true;
1459 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1460 return false;
1461 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1462 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001463 if (Left.is(tok::at) &&
1464 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1465 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001466 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1467 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001468 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001469 if (Left.is(tok::coloncolon))
1470 return false;
1471 if (Right.is(tok::coloncolon))
1472 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001473 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1474 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001475 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001476 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001477 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1478 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001479 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001480 return Right.FormatTok.Tok.isLiteral() ||
1481 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001482 if (Right.is(tok::star) && Left.is(tok::l_paren))
1483 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001484 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1485 return false;
1486 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001487 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001488 if (Left.is(tok::period) || Right.is(tok::period))
1489 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001490 if (Left.is(tok::colon))
1491 return Left.Type != TT_ObjCMethodExpr;
1492 if (Right.is(tok::colon))
1493 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001494 if (Left.is(tok::l_paren))
1495 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001496 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001497 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001498 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001499 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001500 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1501 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001502 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001503 if (Left.is(tok::at) &&
1504 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001505 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001506 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1507 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001508 return true;
1509 }
1510
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001511 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001512 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001513 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1514 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001515 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001516 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001517 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001518 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001519 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001520 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001521 // Don't space between ')' and <id>
1522 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001523 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001524 // Don't space between ':' and '('
1525 return false;
1526 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001527 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001528 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1529 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001530
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001531 if (Tok.Parent->is(tok::comma))
1532 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001533 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001534 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001535 if (Tok.Type == TT_OverloadedOperator)
1536 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001537 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001538 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001539 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001540 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001541 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001542 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001543 if (Tok.Parent->Type == TT_UnaryOperator ||
1544 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001545 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001546 if (Tok.Type == TT_UnaryOperator)
1547 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001548 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1549 (Tok.Parent->isNot(tok::colon) ||
1550 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001551 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1552 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001553 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1554 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001555 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001556 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001557 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001558 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001559 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001560 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001561 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001562 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001563 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001564 }
1565
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001566 bool canBreakBefore(const AnnotatedToken &Right) {
1567 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001568 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001569 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1570 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001571 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001572 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1573 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001574 // Don't break this identifier as ':' or identifier
1575 // before it will break.
1576 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001577 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1578 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001579 // Don't break at ':' if identifier before it can beak.
1580 return false;
1581 }
Nico Webera7252d82013-01-12 06:18:40 +00001582 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1583 return false;
1584 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1585 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001586 if (isObjCSelectorName(Right))
1587 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001588 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001589 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001590 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001591 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001592 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001593 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001594 return false;
1595
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001596 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001597 // We rely on MustBreakBefore being set correctly here as we should not
1598 // change the "binding" behavior of a comment.
1599 return false;
1600
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001601 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1602 // unless it is follow by ';', '{' or '='.
1603 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1604 Left.Parent->is(tok::r_paren))
1605 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1606 Right.isNot(tok::equal);
1607
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001608 // We only break before r_brace if there was a corresponding break before
1609 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1610 if (Right.is(tok::r_brace))
1611 return false;
1612
Daniel Jasper71945272013-01-15 14:27:39 +00001613 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001614 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001615 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1616 Left.is(tok::comma) || Right.is(tok::lessless) ||
1617 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001618 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1619 Left.is(tok::semi) || Left.is(tok::l_brace) ||
1620 Left.is(tok::question) || Left.Type == TT_ConditionalExpr ||
1621 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1622 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001623 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1624 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001625 }
1626
Daniel Jasperf7935112012-12-03 18:12:45 +00001627 FormatStyle Style;
1628 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001629 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001630 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001631};
1632
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001633class LexerBasedFormatTokenSource : public FormatTokenSource {
1634public:
1635 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001636 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001637 IdentTable(Lex.getLangOpts()) {
1638 Lex.SetKeepWhitespaceMode(true);
1639 }
1640
1641 virtual FormatToken getNextToken() {
1642 if (GreaterStashed) {
1643 FormatTok.NewlinesBefore = 0;
1644 FormatTok.WhiteSpaceStart =
1645 FormatTok.Tok.getLocation().getLocWithOffset(1);
1646 FormatTok.WhiteSpaceLength = 0;
1647 GreaterStashed = false;
1648 return FormatTok;
1649 }
1650
1651 FormatTok = FormatToken();
1652 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001653 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001654 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001655 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1656 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001657
1658 // Consume and record whitespace until we find a significant token.
1659 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001660 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001661 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1662 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001663 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1664
1665 if (FormatTok.Tok.is(tok::eof))
1666 return FormatTok;
1667 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001668 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001669 }
Manuel Klimekef920692013-01-07 07:56:50 +00001670
1671 // Now FormatTok is the next non-whitespace token.
1672 FormatTok.TokenLength = Text.size();
1673
Manuel Klimek1abf7892013-01-04 23:34:14 +00001674 // In case the token starts with escaped newlines, we want to
1675 // take them into account as whitespace - this pattern is quite frequent
1676 // in macro definitions.
1677 // FIXME: What do we want to do with other escaped spaces, and escaped
1678 // spaces or newlines in the middle of tokens?
1679 // FIXME: Add a more explicit test.
1680 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001681 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001682 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001683 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001684 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001685 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001686 }
1687
1688 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001689 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001690 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001691 FormatTok.Tok.setKind(Info.getTokenID());
1692 }
1693
1694 if (FormatTok.Tok.is(tok::greatergreater)) {
1695 FormatTok.Tok.setKind(tok::greater);
1696 GreaterStashed = true;
1697 }
1698
1699 return FormatTok;
1700 }
1701
1702private:
1703 FormatToken FormatTok;
1704 bool GreaterStashed;
1705 Lexer &Lex;
1706 SourceManager &SourceMgr;
1707 IdentifierTable IdentTable;
1708
1709 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001710 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001711 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1712 Tok.getLength());
1713 }
1714};
1715
Daniel Jasperf7935112012-12-03 18:12:45 +00001716class Formatter : public UnwrappedLineConsumer {
1717public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001718 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1719 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001720 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001721 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001722 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001723
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001724 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001725
Daniel Jasperf7935112012-12-03 18:12:45 +00001726 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001727 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001728 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001729 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001730 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001731 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1732 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1733 Annotator.annotate();
1734 }
1735 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1736 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001737 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001738 const AnnotatedLine &TheLine = *I;
1739 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1740 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1741 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001742 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001743 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001744 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001745 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001746 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001747 PreviousEndOfLineColumn = Formatter.format();
1748 } else {
1749 // If we did not reformat this unwrapped line, the column at the end of
1750 // the last token is unchanged - thus, we can calculate the end of the
1751 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001752 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001753 SourceMgr.getSpellingColumnNumber(
1754 TheLine.Last->FormatTok.Tok.getLocation()) +
1755 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1756 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001757 1;
1758 }
1759 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001760 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001761 }
1762
1763private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001764 /// \brief Tries to merge lines into one.
1765 ///
1766 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1767 /// if possible; note that \c I will be incremented when lines are merged.
1768 ///
1769 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001770 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001771 std::vector<AnnotatedLine>::iterator &I,
1772 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001773 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1774
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001775 // We can never merge stuff if there are trailing line comments.
1776 if (I->Last->Type == TT_LineComment)
1777 return;
1778
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001779 // Check whether the UnwrappedLine can be put onto a single line. If
1780 // so, this is bound to be the optimal solution (by definition) and we
1781 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001782 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001783 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001784 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001785
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001786 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001787 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001788
Daniel Jasper25837aa2013-01-14 14:14:23 +00001789 if (I->Last->is(tok::l_brace)) {
1790 tryMergeSimpleBlock(I, E, Limit);
1791 } else if (I->First.is(tok::kw_if)) {
1792 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001793 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1794 I->First.FormatTok.IsFirst)) {
1795 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001796 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001797 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001798 }
1799
Daniel Jasper39825ea2013-01-14 15:40:57 +00001800 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1801 std::vector<AnnotatedLine>::iterator E,
1802 unsigned Limit) {
1803 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001804 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1805 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001806 if (I + 2 != E && (I + 2)->InPPDirective &&
1807 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1808 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001809 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001810 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001811 join(Line, *(++I));
1812 }
1813
Daniel Jasper25837aa2013-01-14 14:14:23 +00001814 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1815 std::vector<AnnotatedLine>::iterator E,
1816 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001817 if (!Style.AllowShortIfStatementsOnASingleLine)
1818 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001819 if ((I + 1)->InPPDirective != I->InPPDirective ||
1820 ((I + 1)->InPPDirective &&
1821 (I + 1)->First.FormatTok.HasUnescapedNewline))
1822 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001823 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001824 if (Line.Last->isNot(tok::r_paren))
1825 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001826 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001827 return;
1828 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1829 return;
1830 // Only inline simple if's (no nested if or else).
1831 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1832 return;
1833 join(Line, *(++I));
1834 }
1835
1836 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1837 std::vector<AnnotatedLine>::iterator E,
1838 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001839 // First, check that the current line allows merging. This is the case if
1840 // we're not in a control flow statement and the last token is an opening
1841 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001842 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001843 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001844 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1845 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1846 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1847 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001848 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001849 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1850 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001851 if (!AllowedTokens)
1852 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001853
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001854 AnnotatedToken *Tok = &(I + 1)->First;
1855 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1856 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1857 Tok->SpaceRequiredBefore = false;
1858 join(Line, *(I + 1));
1859 I += 1;
1860 } else {
1861 // Check that we still have three lines and they fit into the limit.
1862 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1863 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001864 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001865
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001866 // Second, check that the next line does not contain any braces - if it
1867 // does, readability declines when putting it into a single line.
1868 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1869 return;
1870 do {
1871 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1872 return;
1873 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1874 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001875
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001876 // Last, check that the third line contains a single closing brace.
1877 Tok = &(I + 2)->First;
1878 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1879 Tok->MustBreakBefore)
1880 return;
1881
1882 join(Line, *(I + 1));
1883 join(Line, *(I + 2));
1884 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001885 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001886 }
1887
1888 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1889 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001890 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1891 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001892 }
1893
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001894 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1895 A.Last->Children.push_back(B.First);
1896 while (!A.Last->Children.empty()) {
1897 A.Last->Children[0].Parent = A.Last;
1898 A.Last = &A.Last->Children[0];
1899 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001900 }
1901
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001902 bool touchesRanges(const AnnotatedLine &TheLine) {
1903 const FormatToken *First = &TheLine.First.FormatTok;
1904 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001905 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001906 First->Tok.getLocation(),
1907 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001908 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001909 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1910 Ranges[i].getBegin()) &&
1911 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1912 LineRange.getBegin()))
1913 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001914 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001915 return false;
1916 }
1917
1918 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001919 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001920 }
1921
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001922 /// \brief Add a new line and the required indent before the first Token
1923 /// of the \c UnwrappedLine if there was no structural parsing error.
1924 /// Returns the indent level of the \c UnwrappedLine.
1925 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1926 bool InPPDirective,
1927 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001928 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001929 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1930 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1931
1932 unsigned Newlines = std::min(Tok.NewlinesBefore,
1933 Style.MaxEmptyLinesToKeep + 1);
1934 if (Newlines == 0 && !Tok.IsFirst)
1935 Newlines = 1;
1936 unsigned Indent = Level * 2;
1937
1938 bool IsAccessModifier = false;
1939 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1940 RootToken.is(tok::kw_private))
1941 IsAccessModifier = true;
1942 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1943 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1944 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1945 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1946 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1947 IsAccessModifier = true;
1948
1949 if (IsAccessModifier &&
1950 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1951 Indent += Style.AccessModifierOffset;
1952 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001953 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001954 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001955 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1956 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001957 }
1958 return Indent;
1959 }
1960
Alexander Kornienko116ba682013-01-14 11:34:14 +00001961 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001962 FormatStyle Style;
1963 Lexer &Lex;
1964 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001965 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001966 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001967 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001968 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001969};
1970
1971tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1972 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001973 std::vector<CharSourceRange> Ranges,
1974 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001975 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001976 OwningPtr<DiagnosticConsumer> DiagPrinter;
1977 if (DiagClient == 0) {
1978 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1979 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1980 DiagClient = DiagPrinter.get();
1981 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001982 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001983 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001984 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001985 Diagnostics.setSourceManager(&SourceMgr);
1986 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001987 return formatter.format();
1988}
1989
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001990LangOptions getFormattingLangOpts() {
1991 LangOptions LangOpts;
1992 LangOpts.CPlusPlus = 1;
1993 LangOpts.CPlusPlus11 = 1;
1994 LangOpts.Bool = 1;
1995 LangOpts.ObjC1 = 1;
1996 LangOpts.ObjC2 = 1;
1997 return LangOpts;
1998}
1999
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002000} // namespace format
2001} // namespace clang