blob: 85f2c32a988df8bfc5b1a479b748edc0686078ed [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),
Daniel Jasperca6623b2013-01-28 12:45:14 +0000436 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jaspera836b902013-01-23 16:58:21 +0000437 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 Jasperca6623b2013-01-28 12:45:14 +0000466 /// \brief The column of a \c ? in a conditional expression;
467 unsigned QuestionColumn;
468
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000469 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000470 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000471
Daniel Jasper337816e2013-01-11 10:22:12 +0000472 bool operator<(const ParenState &Other) const {
473 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000474 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000475 if (LastSpace != Other.LastSpace)
476 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000477 if (AssignmentColumn != Other.AssignmentColumn)
478 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000479 if (FirstLessLess != Other.FirstLessLess)
480 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000481 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
482 return BreakBeforeClosingBrace;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000483 if (QuestionColumn != Other.QuestionColumn)
484 return QuestionColumn < Other.QuestionColumn;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000485 if (BreakAfterComma != Other.BreakAfterComma)
486 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000487 if (HasMultiParameterLine != Other.HasMultiParameterLine)
488 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000489 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000490 }
491 };
492
493 /// \brief The current state when indenting a unwrapped line.
494 ///
495 /// As the indenting tries different combinations this is copied by value.
496 struct LineState {
497 /// \brief The number of used columns in the current line.
498 unsigned Column;
499
500 /// \brief The token that needs to be next formatted.
501 const AnnotatedToken *NextToken;
502
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000503 /// \brief The column of the first variable in a for-loop declaration.
504 ///
505 /// Used to align the second variable if necessary.
506 unsigned ForLoopVariablePos;
507
508 /// \brief \c true if this line contains a continued for-loop section.
509 bool LineContainsContinuedForLoopSection;
510
Daniel Jasper337816e2013-01-11 10:22:12 +0000511 /// \brief A stack keeping track of properties applying to parenthesis
512 /// levels.
513 std::vector<ParenState> Stack;
514
515 /// \brief Comparison operator to be able to used \c LineState in \c map.
516 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000517 if (Other.NextToken != NextToken)
518 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000519 if (Other.Column != Column)
520 return Other.Column > Column;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000521 if (Other.ForLoopVariablePos != ForLoopVariablePos)
522 return Other.ForLoopVariablePos < ForLoopVariablePos;
523 if (Other.LineContainsContinuedForLoopSection !=
524 LineContainsContinuedForLoopSection)
525 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000526 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000527 }
528 };
529
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000530 /// \brief Appends the next token to \p State and updates information
531 /// necessary for indentation.
532 ///
533 /// Puts the token on the current line if \p Newline is \c true and adds a
534 /// line break and necessary indentation otherwise.
535 ///
536 /// If \p DryRun is \c false, also creates and stores the required
537 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000538 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000539 const AnnotatedToken &Current = *State.NextToken;
540 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000541 assert(State.Stack.size());
542 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000543
544 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000545 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000546 if (Current.is(tok::r_brace)) {
547 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000548 } else if (Current.is(tok::string_literal) &&
549 Previous.is(tok::string_literal)) {
550 State.Column = State.Column - Previous.FormatTok.TokenLength;
551 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000552 State.Stack[ParenLevel].FirstLessLess != 0) {
553 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000554 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000555 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
Daniel Jasperca6623b2013-01-28 12:45:14 +0000556 Current.is(tok::period) || Current.is(tok::arrow) ||
557 Current.is(tok::question))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000558 // Indent and extra 4 spaces after if we know the current expression is
559 // continued. Don't do that on the top level, as we already indent 4
560 // there.
Daniel Jasperca6623b2013-01-28 12:45:14 +0000561 State.Column = std::max(State.Stack.back().LastSpace,
562 State.Stack.back().Indent) + 4;
563 } else if (Current.Type == TT_ConditionalExpr) {
564 State.Column = State.Stack.back().QuestionColumn;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000565 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000566 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000567 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000568 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000569 } else if (Previous.Type == TT_BinaryOperator &&
570 State.Stack.back().AssignmentColumn != 0) {
571 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000572 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000573 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000574 }
575
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000576 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000577 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000578
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000579 if (!DryRun) {
580 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000581 Whitespaces.replaceWhitespace(Current, 1, State.Column,
582 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000583 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000584 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
585 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000586 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000587
Daniel Jasper337816e2013-01-11 10:22:12 +0000588 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000589 if (Current.is(tok::colon) && Current.Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000590 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000592 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
593 State.ForLoopVariablePos = State.Column -
594 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000595
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000596 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
597 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000598 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000601 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000602
Daniel Jasperbcab4302013-01-09 10:40:23 +0000603 // FIXME: Do we need to do this for assignments nested in other
604 // expressions?
605 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000606 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000607 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000608 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000609 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000610 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000611 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000612 if (Current.getPreviousNoneComment() != NULL &&
613 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000614 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000615 State.Stack[ParenLevel].HasMultiParameterLine = true;
616
Daniel Jaspere9de2602012-12-06 09:56:08 +0000617 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000618 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
619 // Treat the condition inside an if as if it was a second function
620 // parameter, i.e. let nested calls have an indent of 4.
621 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000622 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000623 // Top-level spaces are exempt as that mostly leads to better results.
624 State.Stack.back().LastSpace = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000625 else if ((Previous.Type == TT_BinaryOperator ||
626 Previous.Type == TT_ConditionalExpr) &&
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000627 getPrecedence(Previous) != prec::Assignment)
628 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000629 else if (Previous.ParameterCount > 1 &&
630 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
631 Previous.Type == TT_TemplateOpener))
632 // If this function has multiple parameters, indent nested calls from
633 // the start of the first parameter.
634 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000635 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000636
637 // If we break after an {, we should also break before the corresponding }.
638 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000639 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000640
Daniel Jaspere941b162013-01-23 10:08:28 +0000641 if (!Style.BinPackParameters && Newline) {
642 // If we are breaking after '(', '{', '<', this is not bin packing unless
643 // AllowAllParametersOnNextLine is false.
644 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
645 Previous.Type != TT_TemplateOpener) ||
646 !Style.AllowAllParametersOnNextLine)
647 State.Stack.back().BreakAfterComma = true;
648
649 // Any break on this level means that the parent level has been broken
650 // and we need to avoid bin packing there.
651 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
652 State.Stack[i].BreakAfterComma = true;
653 }
654 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000655
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000656 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000657 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000658
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000659 /// \brief Mark the next token as consumed in \p State and modify its stacks
660 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000661 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000662 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000663 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000664
Daniel Jasper337816e2013-01-11 10:22:12 +0000665 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
666 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasperca6623b2013-01-28 12:45:14 +0000667 if (Current.is(tok::question))
668 State.Stack.back().QuestionColumn = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000669
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000670 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000671 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000672 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
673 Current.is(tok::l_brace) ||
674 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000675 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000676 if (Current.is(tok::l_brace)) {
677 // FIXME: This does not work with nested static initializers.
678 // Implement a better handling for static initializers and similar
679 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000680 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000681 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000682 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000683 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000684 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000685 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000686 }
687
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000688 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000689 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000690 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
691 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
692 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000693 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000694 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000695
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 if (State.NextToken->Children.empty())
697 State.NextToken = NULL;
698 else
699 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000700
701 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000702 }
703
Nico Weber49cbc2c2013-01-07 15:15:29 +0000704 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000705 unsigned splitPenalty(const AnnotatedToken &Tok) {
706 const AnnotatedToken &Left = Tok;
707 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000708
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000709 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
710 return 50;
711 if (Left.is(tok::equal) && Right.is(tok::l_brace))
712 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000713 if (Left.is(tok::coloncolon))
714 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000715
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000716 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000717 if (RootToken.is(tok::kw_for) &&
718 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000719 return 20;
720
Daniel Jasper04468962013-01-18 10:56:38 +0000721 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000723
724 // In Objective-C method expressions, prefer breaking before "param:" over
725 // breaking after it.
726 if (isObjCSelectorName(Right))
727 return 0;
728 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
729 return 20;
730
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000731 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000732 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000733 // FIXME: The penalty for a trailing "<" or "[" being higher than the
734 // penalty for a trainling "(" is a temporary workaround until we can
735 // properly avoid breaking in array subscripts or template parameters.
736 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
737 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000738
Daniel Jasperca6623b2013-01-28 12:45:14 +0000739 if (Left.Type == TT_ConditionalExpr)
Daniel Jasper399d24b2013-01-09 07:06:56 +0000740 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000741 prec::Level Level = getPrecedence(Left);
742
Daniel Jasperde5c2072012-12-24 00:13:23 +0000743 if (Level != prec::Unknown)
744 return Level;
745
Daniel Jasper04468962013-01-18 10:56:38 +0000746 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000747 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000748 return 5; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000749 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000750 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000751
Daniel Jasperf7935112012-12-03 18:12:45 +0000752 return 3;
753 }
754
Daniel Jasper2df93312013-01-09 10:16:05 +0000755 unsigned getColumnLimit() {
756 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
757 }
758
Daniel Jasperf7935112012-12-03 18:12:45 +0000759 /// \brief Calculate the number of lines needed to format the remaining part
760 /// of the unwrapped line.
761 ///
762 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000763 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000764 /// added after the previous token.
765 ///
766 /// \param StopAt is used for optimization. If we can determine that we'll
767 /// definitely need at least \p StopAt additional lines, we already know of a
768 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000769 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000770 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000771 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000772 return 0;
773
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000774 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000776 if (NewLine && !State.NextToken->CanBreakBefore &&
777 !(State.NextToken->is(tok::r_brace) &&
778 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000779 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000780 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000781 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000782 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000783 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000784 State.LineContainsContinuedForLoopSection)
785 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000786 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000787 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000788 State.Stack.back().BreakAfterComma)
789 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000790 // Trying to insert a parameter on a new line if there are already more than
791 // one parameter on the current line is bin packing.
792 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
793 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
794 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000795 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
796 (State.NextToken->Parent->ClosesTemplateDeclaration &&
797 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000798 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000799
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000800 unsigned CurrentPenalty = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +0000801 if (NewLine)
Daniel Jasper337816e2013-01-11 10:22:12 +0000802 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000803 splitPenalty(*State.NextToken->Parent);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000804
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000805 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000806
Daniel Jasper2df93312013-01-09 10:16:05 +0000807 // Exceeding column limit is bad, assign penalty.
808 if (State.Column > getColumnLimit()) {
809 unsigned ExcessCharacters = State.Column - getColumnLimit();
810 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
811 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000812
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 if (StopAt <= CurrentPenalty)
814 return UINT_MAX;
815 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000816 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000817 if (I != Memory.end()) {
818 // If this state has already been examined, we can safely return the
819 // previous result if we
820 // - have not hit the optimatization (and thus returned UINT_MAX) OR
821 // - are now computing for a smaller or equal StopAt.
822 unsigned SavedResult = I->second.first;
823 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000824 if (SavedResult != UINT_MAX)
825 return SavedResult + CurrentPenalty;
826 else if (StopAt <= SavedStopAt)
827 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000828 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000829
830 unsigned NoBreak = calcPenalty(State, false, StopAt);
831 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
832 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000833
834 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
835 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000836 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000837
838 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 }
840
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 FormatStyle Style;
842 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000843 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000844 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000846 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000847
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000848 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000849 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000850 StateMap Memory;
851
Daniel Jasperf7935112012-12-03 18:12:45 +0000852 OptimizationParameters Parameters;
853};
854
855/// \brief Determines extra information about the tokens comprising an
856/// \c UnwrappedLine.
857class TokenAnnotator {
858public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000859 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
860 AnnotatedLine &Line)
861 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000862
863 /// \brief A parser that gathers additional information about tokens.
864 ///
865 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
866 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
867 /// into template parameter lists.
868 class AnnotatingParser {
869 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000871 : CurrentToken(&RootToken), KeywordVirtualFound(false),
872 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000873
Nico Weber250fe712013-01-18 02:43:57 +0000874 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
875 struct ObjCSelectorRAII {
876 AnnotatingParser &P;
877 bool ColonWasObjCMethodExpr;
878
879 ObjCSelectorRAII(AnnotatingParser &P)
880 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
881
882 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
883
884 void markStart(AnnotatedToken &Left) {
885 P.ColonIsObjCMethodExpr = true;
886 Left.Type = TT_ObjCMethodExpr;
887 }
888
889 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
890 };
891
892
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000893 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000894 if (CurrentToken == NULL)
895 return false;
896 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000897 while (CurrentToken != NULL) {
898 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000899 Left->MatchingParen = CurrentToken;
900 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000902 next();
903 return true;
904 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000905 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
906 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000907 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000908 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
909 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000910 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000911 if (CurrentToken->is(tok::comma))
912 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000913 if (!consumeToken())
914 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 }
916 return false;
917 }
918
Nico Weber80a82762013-01-17 17:17:19 +0000919 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000920 if (CurrentToken == NULL)
921 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000922 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000923 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000924 if (CurrentToken->is(tok::caret)) {
925 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000926 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000927 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
928 // @selector( starts a selector.
929 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
930 MaybeSel->Parent->is(tok::at)) {
931 StartsObjCMethodExpr = true;
932 }
933 }
934
935 ObjCSelectorRAII objCSelector(*this);
936 if (StartsObjCMethodExpr)
937 objCSelector.markStart(*Left);
938
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000939 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000940 // LookForDecls is set when "if (" has been seen. Check for
941 // 'identifier' '*' 'identifier' followed by not '=' -- this
942 // '*' has to be a binary operator but determineStarAmpUsage() will
943 // categorize it as an unary operator, so set the right type here.
944 if (LookForDecls && !CurrentToken->Children.empty()) {
945 AnnotatedToken &Prev = *CurrentToken->Parent;
946 AnnotatedToken &Next = CurrentToken->Children[0];
947 if (Prev.Parent->is(tok::identifier) &&
948 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
949 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
950 Prev.Type = TT_BinaryOperator;
951 LookForDecls = false;
952 }
953 }
954
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000955 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000956 Left->MatchingParen = CurrentToken;
957 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000958
959 if (StartsObjCMethodExpr)
960 objCSelector.markEnd(*CurrentToken);
961
Daniel Jasperf7935112012-12-03 18:12:45 +0000962 next();
963 return true;
964 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000965 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000966 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000967 if (CurrentToken->is(tok::comma))
968 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000969 if (!consumeToken())
970 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000971 }
972 return false;
973 }
974
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000975 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000976 if (!CurrentToken)
977 return false;
978
979 // A '[' could be an index subscript (after an indentifier or after
980 // ')' or ']'), or it could be the start of an Objective-C method
981 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000982 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000983 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000984 !Left->Parent || Left->Parent->is(tok::colon) ||
985 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
986 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
987 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000988 true, true) > prec::Unknown;
989
Nico Weber250fe712013-01-18 02:43:57 +0000990 ObjCSelectorRAII objCSelector(*this);
991 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000992 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000993
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000994 while (CurrentToken != NULL) {
995 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000996 if (!CurrentToken->Children.empty() &&
997 CurrentToken->Children[0].is(tok::l_paren)) {
998 // An ObjC method call can't be followed by an open parenthesis.
999 // FIXME: Do we incorrectly label ":" with this?
1000 StartsObjCMethodExpr = false;
1001 Left->Type = TT_Unknown;
1002 }
Nico Weber250fe712013-01-18 02:43:57 +00001003 if (StartsObjCMethodExpr)
1004 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001005 Left->MatchingParen = CurrentToken;
1006 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 next();
1008 return true;
1009 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001011 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001012 if (CurrentToken->is(tok::comma))
1013 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001014 if (!consumeToken())
1015 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 }
1017 return false;
1018 }
1019
Daniel Jasper83a54d22013-01-10 09:26:47 +00001020 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001021 // Lines are fine to end with '{'.
1022 if (CurrentToken == NULL)
1023 return true;
1024 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001025 while (CurrentToken != NULL) {
1026 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001027 Left->MatchingParen = CurrentToken;
1028 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001029 next();
1030 return true;
1031 }
1032 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1033 return false;
1034 if (!consumeToken())
1035 return false;
1036 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001037 return true;
1038 }
1039
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001040 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001041 while (CurrentToken != NULL) {
1042 if (CurrentToken->is(tok::colon)) {
1043 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 next();
1045 return true;
1046 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001047 if (!consumeToken())
1048 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 }
1050 return false;
1051 }
1052
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001053 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1055 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001056 next();
1057 if (!parseAngle())
1058 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001059 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001060 return true;
1061 }
1062 return false;
1063 }
1064
Daniel Jasperc0880a92013-01-04 18:52:56 +00001065 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001066 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001067 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001069 case tok::plus:
1070 case tok::minus:
1071 // At the start of the line, +/- specific ObjectiveC method
1072 // declarations.
1073 if (Tok->Parent == NULL)
1074 Tok->Type = TT_ObjCMethodSpecifier;
1075 break;
Nico Webera7252d82013-01-12 06:18:40 +00001076 case tok::colon:
1077 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001078 if (Tok->Parent->is(tok::r_paren))
1079 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001080 if (ColonIsObjCMethodExpr)
1081 Tok->Type = TT_ObjCMethodExpr;
1082 break;
Nico Weber80a82762013-01-17 17:17:19 +00001083 case tok::kw_if:
1084 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001085 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001086 next();
1087 if (!parseParens(/*LookForDecls=*/true))
1088 return false;
1089 }
1090 break;
Nico Webera5510af2013-01-18 05:50:57 +00001091 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001092 if (!parseParens())
1093 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001094 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001095 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001096 if (!parseSquare())
1097 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001098 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001099 case tok::l_brace:
1100 if (!parseBrace())
1101 return false;
1102 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001103 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001104 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001105 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001106 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001107 Tok->Type = TT_BinaryOperator;
1108 CurrentToken = Tok;
1109 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001110 }
1111 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001112 case tok::r_paren:
1113 case tok::r_square:
1114 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001115 case tok::r_brace:
1116 // Lines can start with '}'.
1117 if (Tok->Parent != NULL)
1118 return false;
1119 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001120 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001122 break;
1123 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001124 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001125 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001126 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001127 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1128 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001129 next();
1130 }
1131 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1133 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001134 next();
1135 }
1136 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 break;
1138 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001139 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001140 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001141 case tok::kw_template:
1142 parseTemplateDeclaration();
1143 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001144 default:
1145 break;
1146 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001147 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001148 }
1149
Daniel Jasper050948a52012-12-21 17:58:39 +00001150 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001151 next();
1152 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1153 next();
1154 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001155 if (CurrentToken->isNot(tok::comment) ||
1156 !CurrentToken->Children.empty())
1157 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001158 next();
1159 }
1160 } else {
1161 while (CurrentToken != NULL) {
1162 next();
1163 }
1164 }
1165 }
1166
1167 void parseWarningOrError() {
1168 next();
1169 // We still want to format the whitespace left of the first token of the
1170 // warning or error.
1171 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001172 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001173 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001174 next();
1175 }
1176 }
1177
1178 void parsePreprocessorDirective() {
1179 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001180 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001181 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001182 // Hashes in the middle of a line can lead to any strange token
1183 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001184 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001185 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001186 switch (
1187 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001188 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001189 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001190 parseIncludeDirective();
1191 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001192 case tok::pp_error:
1193 case tok::pp_warning:
1194 parseWarningOrError();
1195 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001196 default:
1197 break;
1198 }
1199 }
1200
Daniel Jasperda16db32013-01-07 10:48:50 +00001201 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001202 int PeriodsAndArrows = 0;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001203 bool CanBeBuilderTypeStmt = true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001204 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001205 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001206 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001207 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001208 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001209
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001210 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001211 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001212 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1213 ++PeriodsAndArrows;
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001214 if (getPrecedence(*CurrentToken) > prec::Assignment &&
1215 CurrentToken->isNot(tok::less) && CurrentToken->isNot(tok::greater))
1216 CanBeBuilderTypeStmt = false;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001217 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001218 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001219 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001220 if (KeywordVirtualFound)
1221 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001222
1223 // Assume a builder-type call if there are 2 or more "." and "->".
Daniel Jasper20b09ef2013-01-28 09:35:24 +00001224 if (PeriodsAndArrows >= 2 && CanBeBuilderTypeStmt)
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001225 return LT_BuilderTypeCall;
1226
Daniel Jasperda16db32013-01-07 10:48:50 +00001227 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001228 }
1229
1230 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001231 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1232 CurrentToken = &CurrentToken->Children[0];
1233 else
1234 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001235 }
1236
1237 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001238 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001239 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001240 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001241 };
1242
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 void calculateExtraInformation(AnnotatedToken &Current) {
1244 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1245
Manuel Klimek52b15152013-01-09 15:25:02 +00001246 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001247 Current.MustBreakBefore = true;
1248 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001249 if (Current.Type == TT_LineComment) {
1250 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001251 } else if ((Current.Parent->is(tok::comment) &&
1252 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001253 (Current.is(tok::string_literal) &&
1254 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001255 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001256 } else {
1257 Current.MustBreakBefore = false;
1258 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001259 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001260 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001261 if (Current.MustBreakBefore)
1262 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1263 else
1264 Current.TotalLength = Current.Parent->TotalLength +
1265 Current.FormatTok.TokenLength +
1266 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001267 if (!Current.Children.empty())
1268 calculateExtraInformation(Current.Children[0]);
1269 }
1270
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001271 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001272 AnnotatingParser Parser(Line.First);
1273 Line.Type = Parser.parseLine();
1274 if (Line.Type == LT_Invalid)
1275 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001276
Daniel Jasper5b49f472013-01-23 12:10:53 +00001277 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001278
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001279 if (Line.First.Type == TT_ObjCMethodSpecifier)
1280 Line.Type = LT_ObjCMethodDecl;
1281 else if (Line.First.Type == TT_ObjCDecl)
1282 Line.Type = LT_ObjCDecl;
1283 else if (Line.First.Type == TT_ObjCProperty)
1284 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001285
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001286 Line.First.SpaceRequiredBefore = true;
1287 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1288 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001289
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001290 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001291 if (!Line.First.Children.empty())
1292 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001293 }
1294
1295private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001296 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1297 if (getPrecedence(Current) == prec::Assignment) {
1298 IsExpression = true;
1299 AnnotatedToken *Previous = Current.Parent;
1300 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001301 if (Previous->Type == TT_BinaryOperator &&
1302 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001303 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001304 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001305 Previous = Previous->Parent;
1306 }
1307 }
1308 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001309 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1310 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001311 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001312
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001313 if (Current.Type == TT_Unknown) {
1314 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001315 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001316 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1317 Current.is(tok::caret)) {
1318 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001319 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1320 Current.Type = determineIncrementUsage(Current);
1321 } else if (Current.is(tok::exclaim)) {
1322 Current.Type = TT_UnaryOperator;
1323 } else if (isBinaryOperator(Current)) {
1324 Current.Type = TT_BinaryOperator;
1325 } else if (Current.is(tok::comment)) {
1326 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1327 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001328 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001329 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001330 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001331 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001332 } else if (Current.is(tok::r_paren) &&
1333 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001334 Current.Parent->Type == TT_TemplateCloser) &&
1335 (Current.Children.empty() ||
1336 (Current.Children[0].isNot(tok::equal) &&
1337 Current.Children[0].isNot(tok::semi) &&
1338 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001339 // FIXME: We need to get smarter and understand more cases of casts.
1340 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001341 } else if (Current.is(tok::at) && Current.Children.size()) {
1342 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1343 case tok::objc_interface:
1344 case tok::objc_implementation:
1345 case tok::objc_protocol:
1346 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001347 break;
1348 case tok::objc_property:
1349 Current.Type = TT_ObjCProperty;
1350 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001351 default:
1352 break;
1353 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001354 }
1355 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001356
1357 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001358 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001359 }
1360
Daniel Jasper71945272013-01-15 14:27:39 +00001361 /// \brief Returns the previous token ignoring comments.
1362 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1363 const AnnotatedToken *PrevToken = Tok.Parent;
1364 while (PrevToken != NULL && PrevToken->is(tok::comment))
1365 PrevToken = PrevToken->Parent;
1366 return PrevToken;
1367 }
1368
1369 /// \brief Returns the next token ignoring comments.
1370 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1371 if (Tok.Children.empty())
1372 return NULL;
1373 const AnnotatedToken *NextToken = &Tok.Children[0];
1374 while (NextToken->is(tok::comment)) {
1375 if (NextToken->Children.empty())
1376 return NULL;
1377 NextToken = &NextToken->Children[0];
1378 }
1379 return NextToken;
1380 }
1381
1382 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001383 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1384 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001385 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1386 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001387 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001388
1389 const AnnotatedToken *NextToken = getNextToken(Tok);
1390 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001391 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001392
Daniel Jasper0b820602013-01-22 11:46:26 +00001393 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1394 return TT_PointerOrReference;
1395
Daniel Jasper71945272013-01-15 14:27:39 +00001396 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1397 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1398 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1399 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001400 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001401 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001402
Daniel Jasper71945272013-01-15 14:27:39 +00001403 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1404 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1405 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1406 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1407 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1408 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1409 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001410 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001411
Daniel Jasper71945272013-01-15 14:27:39 +00001412 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1413 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001414 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001415
Daniel Jasper426702d2012-12-05 07:51:39 +00001416 // It is very unlikely that we are going to find a pointer or reference type
1417 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001418 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001419 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001420
Daniel Jasperda16db32013-01-07 10:48:50 +00001421 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001422 }
1423
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001424 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001425 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1426 if (PrevToken == NULL)
1427 return TT_UnaryOperator;
1428
Daniel Jasper8dd40472012-12-21 09:41:31 +00001429 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001430 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1431 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1432 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1433 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1434 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001435 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001436
1437 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001438 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001439 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001440
1441 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001442 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001443 }
1444
1445 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001446 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001447 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1448 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001449 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001450 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1451 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001452 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001453
Daniel Jasperda16db32013-01-07 10:48:50 +00001454 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001455 }
1456
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001457 bool spaceRequiredBetween(const AnnotatedToken &Left,
1458 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001459 if (Right.is(tok::hashhash))
1460 return Left.is(tok::hash);
1461 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1462 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001463 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1464 return false;
Nico Webera6087752013-01-10 20:12:55 +00001465 if (Right.is(tok::less) &&
1466 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001467 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001468 return true;
1469 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1470 return false;
1471 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1472 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001473 if (Left.is(tok::at) &&
1474 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1475 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001476 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1477 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001478 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001479 if (Left.is(tok::coloncolon))
1480 return false;
1481 if (Right.is(tok::coloncolon))
1482 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001483 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1484 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001485 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001486 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001487 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1488 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001489 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001490 return Right.FormatTok.Tok.isLiteral() ||
1491 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001492 if (Right.is(tok::star) && Left.is(tok::l_paren))
1493 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001494 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1495 return false;
1496 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001497 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001498 if (Left.is(tok::period) || Right.is(tok::period))
1499 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001500 if (Left.is(tok::colon))
1501 return Left.Type != TT_ObjCMethodExpr;
1502 if (Right.is(tok::colon))
1503 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001504 if (Left.is(tok::l_paren))
1505 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001506 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001507 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001508 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001509 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001510 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1511 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001512 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001513 if (Left.is(tok::at) &&
1514 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001515 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001516 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1517 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001518 return true;
1519 }
1520
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001521 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001522 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001523 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1524 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001525 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001526 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001527 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001528 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001529 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001530 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001531 // Don't space between ')' and <id>
1532 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001533 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001534 // Don't space between ':' and '('
1535 return false;
1536 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001537 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001538 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1539 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001540
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001541 if (Tok.Parent->is(tok::comma))
1542 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001543 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001544 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001545 if (Tok.Type == TT_OverloadedOperator)
1546 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001547 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001548 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001549 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001550 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001551 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001552 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001553 if (Tok.Parent->Type == TT_UnaryOperator ||
1554 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001555 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001556 if (Tok.Type == TT_UnaryOperator)
1557 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001558 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1559 (Tok.Parent->isNot(tok::colon) ||
1560 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001561 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1562 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001563 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1564 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001565 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001566 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001567 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001568 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001569 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001570 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001571 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001572 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001573 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001574 }
1575
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001576 bool canBreakBefore(const AnnotatedToken &Right) {
1577 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001578 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001579 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1580 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001581 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001582 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1583 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001584 // Don't break this identifier as ':' or identifier
1585 // before it will break.
1586 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001587 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1588 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001589 // Don't break at ':' if identifier before it can beak.
1590 return false;
1591 }
Nico Webera7252d82013-01-12 06:18:40 +00001592 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1593 return false;
1594 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1595 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001596 if (isObjCSelectorName(Right))
1597 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001598 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001599 return true;
Daniel Jasperca6623b2013-01-28 12:45:14 +00001600 if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
1601 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001602 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasperca6623b2013-01-28 12:45:14 +00001603 Left.Type == TT_UnaryOperator || Left.Type == TT_ConditionalExpr ||
1604 Left.is(tok::question))
Daniel Jasperd1926a32013-01-02 08:44:14 +00001605 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001606 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001607 return false;
1608
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001609 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001610 // We rely on MustBreakBefore being set correctly here as we should not
1611 // change the "binding" behavior of a comment.
1612 return false;
1613
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001614 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1615 // unless it is follow by ';', '{' or '='.
1616 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1617 Left.Parent->is(tok::r_paren))
1618 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1619 Right.isNot(tok::equal);
1620
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001621 // We only break before r_brace if there was a corresponding break before
1622 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1623 if (Right.is(tok::r_brace))
1624 return false;
1625
Daniel Jasper71945272013-01-15 14:27:39 +00001626 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001627 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001628 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1629 Left.is(tok::comma) || Right.is(tok::lessless) ||
1630 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001631 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1632 Left.is(tok::semi) || Left.is(tok::l_brace) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001633 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1634 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001635 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1636 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001637 }
1638
Daniel Jasperf7935112012-12-03 18:12:45 +00001639 FormatStyle Style;
1640 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001641 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001642 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001643};
1644
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001645class LexerBasedFormatTokenSource : public FormatTokenSource {
1646public:
1647 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001648 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001649 IdentTable(Lex.getLangOpts()) {
1650 Lex.SetKeepWhitespaceMode(true);
1651 }
1652
1653 virtual FormatToken getNextToken() {
1654 if (GreaterStashed) {
1655 FormatTok.NewlinesBefore = 0;
1656 FormatTok.WhiteSpaceStart =
1657 FormatTok.Tok.getLocation().getLocWithOffset(1);
1658 FormatTok.WhiteSpaceLength = 0;
1659 GreaterStashed = false;
1660 return FormatTok;
1661 }
1662
1663 FormatTok = FormatToken();
1664 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001665 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001666 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001667 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1668 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001669
1670 // Consume and record whitespace until we find a significant token.
1671 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001672 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001673 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1674 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001675 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1676
1677 if (FormatTok.Tok.is(tok::eof))
1678 return FormatTok;
1679 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001680 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001681 }
Manuel Klimekef920692013-01-07 07:56:50 +00001682
1683 // Now FormatTok is the next non-whitespace token.
1684 FormatTok.TokenLength = Text.size();
1685
Manuel Klimek1abf7892013-01-04 23:34:14 +00001686 // In case the token starts with escaped newlines, we want to
1687 // take them into account as whitespace - this pattern is quite frequent
1688 // in macro definitions.
1689 // FIXME: What do we want to do with other escaped spaces, and escaped
1690 // spaces or newlines in the middle of tokens?
1691 // FIXME: Add a more explicit test.
1692 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001693 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001694 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001695 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001696 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001697 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001698 }
1699
1700 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001701 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001702 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001703 FormatTok.Tok.setKind(Info.getTokenID());
1704 }
1705
1706 if (FormatTok.Tok.is(tok::greatergreater)) {
1707 FormatTok.Tok.setKind(tok::greater);
1708 GreaterStashed = true;
1709 }
1710
1711 return FormatTok;
1712 }
1713
1714private:
1715 FormatToken FormatTok;
1716 bool GreaterStashed;
1717 Lexer &Lex;
1718 SourceManager &SourceMgr;
1719 IdentifierTable IdentTable;
1720
1721 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001722 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001723 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1724 Tok.getLength());
1725 }
1726};
1727
Daniel Jasperf7935112012-12-03 18:12:45 +00001728class Formatter : public UnwrappedLineConsumer {
1729public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001730 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1731 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001732 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001733 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001734 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001735
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001736 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001737
Daniel Jasperf7935112012-12-03 18:12:45 +00001738 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001739 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001740 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001741 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001742 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001743 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1744 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1745 Annotator.annotate();
1746 }
1747 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1748 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001749 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001750 const AnnotatedLine &TheLine = *I;
1751 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1752 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1753 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001754 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001755 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001756 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001757 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001758 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001759 PreviousEndOfLineColumn = Formatter.format();
1760 } else {
1761 // If we did not reformat this unwrapped line, the column at the end of
1762 // the last token is unchanged - thus, we can calculate the end of the
1763 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001764 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001765 SourceMgr.getSpellingColumnNumber(
1766 TheLine.Last->FormatTok.Tok.getLocation()) +
1767 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1768 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001769 1;
1770 }
1771 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001772 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001773 }
1774
1775private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001776 /// \brief Tries to merge lines into one.
1777 ///
1778 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1779 /// if possible; note that \c I will be incremented when lines are merged.
1780 ///
1781 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001782 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001783 std::vector<AnnotatedLine>::iterator &I,
1784 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001785 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1786
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001787 // We can never merge stuff if there are trailing line comments.
1788 if (I->Last->Type == TT_LineComment)
1789 return;
1790
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001791 // Check whether the UnwrappedLine can be put onto a single line. If
1792 // so, this is bound to be the optimal solution (by definition) and we
1793 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001794 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001795 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001796 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001797
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001798 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001799 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001800
Daniel Jasper25837aa2013-01-14 14:14:23 +00001801 if (I->Last->is(tok::l_brace)) {
1802 tryMergeSimpleBlock(I, E, Limit);
1803 } else if (I->First.is(tok::kw_if)) {
1804 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001805 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1806 I->First.FormatTok.IsFirst)) {
1807 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001808 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001809 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001810 }
1811
Daniel Jasper39825ea2013-01-14 15:40:57 +00001812 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1813 std::vector<AnnotatedLine>::iterator E,
1814 unsigned Limit) {
1815 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001816 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1817 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001818 if (I + 2 != E && (I + 2)->InPPDirective &&
1819 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1820 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001821 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001822 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001823 join(Line, *(++I));
1824 }
1825
Daniel Jasper25837aa2013-01-14 14:14:23 +00001826 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1827 std::vector<AnnotatedLine>::iterator E,
1828 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001829 if (!Style.AllowShortIfStatementsOnASingleLine)
1830 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001831 if ((I + 1)->InPPDirective != I->InPPDirective ||
1832 ((I + 1)->InPPDirective &&
1833 (I + 1)->First.FormatTok.HasUnescapedNewline))
1834 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001835 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001836 if (Line.Last->isNot(tok::r_paren))
1837 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001838 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001839 return;
1840 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1841 return;
1842 // Only inline simple if's (no nested if or else).
1843 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1844 return;
1845 join(Line, *(++I));
1846 }
1847
1848 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1849 std::vector<AnnotatedLine>::iterator E,
1850 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001851 // First, check that the current line allows merging. This is the case if
1852 // we're not in a control flow statement and the last token is an opening
1853 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001854 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001855 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001856 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1857 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1858 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1859 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001860 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001861 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1862 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001863 if (!AllowedTokens)
1864 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001865
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001866 AnnotatedToken *Tok = &(I + 1)->First;
1867 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1868 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1869 Tok->SpaceRequiredBefore = false;
1870 join(Line, *(I + 1));
1871 I += 1;
1872 } else {
1873 // Check that we still have three lines and they fit into the limit.
1874 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1875 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001876 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001877
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001878 // Second, check that the next line does not contain any braces - if it
1879 // does, readability declines when putting it into a single line.
1880 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1881 return;
1882 do {
1883 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1884 return;
1885 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1886 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001887
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001888 // Last, check that the third line contains a single closing brace.
1889 Tok = &(I + 2)->First;
1890 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1891 Tok->MustBreakBefore)
1892 return;
1893
1894 join(Line, *(I + 1));
1895 join(Line, *(I + 2));
1896 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001897 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001898 }
1899
1900 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1901 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001902 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1903 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001904 }
1905
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001906 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1907 A.Last->Children.push_back(B.First);
1908 while (!A.Last->Children.empty()) {
1909 A.Last->Children[0].Parent = A.Last;
1910 A.Last = &A.Last->Children[0];
1911 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001912 }
1913
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001914 bool touchesRanges(const AnnotatedLine &TheLine) {
1915 const FormatToken *First = &TheLine.First.FormatTok;
1916 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001917 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001918 First->Tok.getLocation(),
1919 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001920 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001921 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1922 Ranges[i].getBegin()) &&
1923 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1924 LineRange.getBegin()))
1925 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001926 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001927 return false;
1928 }
1929
1930 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001931 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001932 }
1933
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001934 /// \brief Add a new line and the required indent before the first Token
1935 /// of the \c UnwrappedLine if there was no structural parsing error.
1936 /// Returns the indent level of the \c UnwrappedLine.
1937 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1938 bool InPPDirective,
1939 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001940 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001941 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1942 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1943
1944 unsigned Newlines = std::min(Tok.NewlinesBefore,
1945 Style.MaxEmptyLinesToKeep + 1);
1946 if (Newlines == 0 && !Tok.IsFirst)
1947 Newlines = 1;
1948 unsigned Indent = Level * 2;
1949
1950 bool IsAccessModifier = false;
1951 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1952 RootToken.is(tok::kw_private))
1953 IsAccessModifier = true;
1954 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1955 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1956 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1957 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1958 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1959 IsAccessModifier = true;
1960
1961 if (IsAccessModifier &&
1962 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1963 Indent += Style.AccessModifierOffset;
1964 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001965 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001966 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001967 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1968 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001969 }
1970 return Indent;
1971 }
1972
Alexander Kornienko116ba682013-01-14 11:34:14 +00001973 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001974 FormatStyle Style;
1975 Lexer &Lex;
1976 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001977 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001978 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001979 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001980 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001981};
1982
1983tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1984 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001985 std::vector<CharSourceRange> Ranges,
1986 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001987 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001988 OwningPtr<DiagnosticConsumer> DiagPrinter;
1989 if (DiagClient == 0) {
1990 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1991 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1992 DiagClient = DiagPrinter.get();
1993 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001994 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001995 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001996 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001997 Diagnostics.setSourceManager(&SourceMgr);
1998 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001999 return formatter.format();
2000}
2001
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002002LangOptions getFormattingLangOpts() {
2003 LangOptions LangOpts;
2004 LangOpts.CPlusPlus = 1;
2005 LangOpts.CPlusPlus11 = 1;
2006 LangOpts.Bool = 1;
2007 LangOpts.ObjC1 = 1;
2008 LangOpts.ObjC2 = 1;
2009 return LangOpts;
2010}
2011
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002012} // namespace format
2013} // namespace clang