blob: 1cac334125b3e4910d2e41bbde6785d0517ca3cd [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 Jasper9278eb92013-01-16 14:59:02 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000077
Daniel Jasper25837aa2013-01-14 14:14:23 +000078 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
79 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
80
Daniel Jasper7c85fde2013-01-08 14:56:18 +000081 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
82 return FormatTok.Tok.isObjCAtKeyword(Kind);
83 }
84
85 FormatToken FormatTok;
86
Daniel Jasperf7935112012-12-03 18:12:45 +000087 TokenType Type;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 bool SpaceRequiredBefore;
90 bool CanBreakBefore;
91 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000092
93 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000094
Daniel Jasper9278eb92013-01-16 14:59:02 +000095 AnnotatedToken *MatchingParen;
96
Daniel Jaspera67a8f02013-01-16 10:41:46 +000097 /// \brief The total length of the line up to and including this token.
98 unsigned TotalLength;
99
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000100 std::vector<AnnotatedToken> Children;
101 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000102
103 const AnnotatedToken *getPreviousNoneComment() const {
104 AnnotatedToken *Tok = Parent;
105 while (Tok != NULL && Tok->is(tok::comment))
106 Tok = Tok->Parent;
107 return Tok;
108 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000109};
110
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000111class AnnotatedLine {
112public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000113 AnnotatedLine(const UnwrappedLine &Line)
114 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000115 InPPDirective(Line.InPPDirective),
116 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000117 assert(!Line.Tokens.empty());
118 AnnotatedToken *Current = &First;
119 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
120 E = Line.Tokens.end();
121 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000122 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000123 Current->Children[0].Parent = Current;
124 Current = &Current->Children[0];
125 }
126 Last = Current;
127 }
128 AnnotatedLine(const AnnotatedLine &Other)
129 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000130 InPPDirective(Other.InPPDirective),
131 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000132 Last = &First;
133 while (!Last->Children.empty()) {
134 Last->Children[0].Parent = Last;
135 Last = &Last->Children[0];
136 }
137 }
138
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000139 AnnotatedToken First;
140 AnnotatedToken *Last;
141
142 LineType Type;
143 unsigned Level;
144 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000145 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000146};
147
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000148static prec::Level getPrecedence(const AnnotatedToken &Tok) {
149 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000150}
151
Daniel Jasperf7935112012-12-03 18:12:45 +0000152FormatStyle getLLVMStyle() {
153 FormatStyle LLVMStyle;
154 LLVMStyle.ColumnLimit = 80;
155 LLVMStyle.MaxEmptyLinesToKeep = 1;
156 LLVMStyle.PointerAndReferenceBindToType = false;
157 LLVMStyle.AccessModifierOffset = -2;
158 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000159 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000160 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000161 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000162 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000163 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000164 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000165 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000166 return LLVMStyle;
167}
168
169FormatStyle getGoogleStyle() {
170 FormatStyle GoogleStyle;
171 GoogleStyle.ColumnLimit = 80;
172 GoogleStyle.MaxEmptyLinesToKeep = 1;
173 GoogleStyle.PointerAndReferenceBindToType = true;
174 GoogleStyle.AccessModifierOffset = -1;
175 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000176 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000177 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000178 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000179 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000180 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000181 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000182 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000183 return GoogleStyle;
184}
185
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000186FormatStyle getChromiumStyle() {
187 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000188 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000189 return ChromiumStyle;
190}
191
Daniel Jasperf7935112012-12-03 18:12:45 +0000192struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000193 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000194 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000195 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000196};
197
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000198/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000199///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000200/// This includes special handling for certain constructs, e.g. the alignment of
201/// trailing line comments.
202class WhitespaceManager {
203public:
204 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
205
206 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
207 /// each \c AnnotatedToken.
208 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
209 unsigned Spaces, unsigned WhitespaceStartColumn,
210 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000211 // 2+ newlines mean an empty line separating logic scopes.
212 if (NewLines >= 2)
213 alignComments();
214
215 // Align line comments if they are trailing or if they continue other
216 // trailing comments.
217 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000218 (Tok.Parent != NULL || !Comments.empty())) {
219 if (Style.ColumnLimit >=
220 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
221 Comments.push_back(StoredComment());
222 Comments.back().Tok = Tok.FormatTok;
223 Comments.back().Spaces = Spaces;
224 Comments.back().NewLines = NewLines;
225 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
226 Comments.back().MaxColumn = Style.ColumnLimit -
227 Spaces - Tok.FormatTok.TokenLength;
228 return;
229 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000230 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000231
232 // If this line does not have a trailing comment, align the stored comments.
233 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
234 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000235 storeReplacement(Tok.FormatTok,
236 std::string(NewLines, '\n') + std::string(Spaces, ' '));
237 }
238
239 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
240 /// backslashes to escape newlines inside a preprocessor directive.
241 ///
242 /// This function and \c replaceWhitespace have the same behavior if
243 /// \c Newlines == 0.
244 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
245 unsigned Spaces, unsigned WhitespaceStartColumn,
246 const FormatStyle &Style) {
247 std::string NewLineText;
248 if (NewLines > 0) {
249 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
250 WhitespaceStartColumn);
251 for (unsigned i = 0; i < NewLines; ++i) {
252 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
253 NewLineText += "\\\n";
254 Offset = 0;
255 }
256 }
257 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
258 }
259
260 /// \brief Returns all the \c Replacements created during formatting.
261 const tooling::Replacements &generateReplacements() {
262 alignComments();
263 return Replaces;
264 }
265
266private:
267 /// \brief Structure to store a comment for later layout and alignment.
268 struct StoredComment {
269 FormatToken Tok;
270 unsigned MinColumn;
271 unsigned MaxColumn;
272 unsigned NewLines;
273 unsigned Spaces;
274 };
275 SmallVector<StoredComment, 16> Comments;
276 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
277
278 /// \brief Try to align all stashed comments.
279 void alignComments() {
280 unsigned MinColumn = 0;
281 unsigned MaxColumn = UINT_MAX;
282 comment_iterator Start = Comments.begin();
283 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
284 ++I) {
285 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
286 alignComments(Start, I, MinColumn);
287 MinColumn = I->MinColumn;
288 MaxColumn = I->MaxColumn;
289 Start = I;
290 } else {
291 MinColumn = std::max(MinColumn, I->MinColumn);
292 MaxColumn = std::min(MaxColumn, I->MaxColumn);
293 }
294 }
295 alignComments(Start, Comments.end(), MinColumn);
296 Comments.clear();
297 }
298
299 /// \brief Put all the comments between \p I and \p E into \p Column.
300 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
301 while (I != E) {
302 unsigned Spaces = I->Spaces + Column - I->MinColumn;
303 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
304 std::string(Spaces, ' '));
305 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000306 }
307 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000308
309 /// \brief Stores \p Text as the replacement for the whitespace in front of
310 /// \p Tok.
311 void storeReplacement(const FormatToken &Tok, const std::string Text) {
312 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
313 Tok.WhiteSpaceLength, Text));
314 }
315
316 SourceManager &SourceMgr;
317 tooling::Replacements Replaces;
318};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000319
Nico Weberc9d73612013-01-12 22:48:47 +0000320/// \brief Returns if a token is an Objective-C selector name.
321///
Nico Weber92c05392013-01-12 22:51:13 +0000322/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000323static bool isObjCSelectorName(const AnnotatedToken &Tok) {
324 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
325 Tok.Children[0].is(tok::colon) &&
326 Tok.Children[0].Type == TT_ObjCMethodExpr;
327}
328
Daniel Jasperf7935112012-12-03 18:12:45 +0000329class UnwrappedLineFormatter {
330public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000331 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000332 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000333 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000334 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000335 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000336 FirstIndent(FirstIndent), RootToken(RootToken),
337 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000338 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000339 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000340 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000341 }
342
Manuel Klimek1abf7892013-01-04 23:34:14 +0000343 /// \brief Formats an \c UnwrappedLine.
344 ///
345 /// \returns The column after the last token in the last line of the
346 /// \c UnwrappedLine.
347 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000348 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000349 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000350 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000351 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000352 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000353 State.ForLoopVariablePos = 0;
354 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000355 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000356
Manuel Klimek24998102013-01-16 14:55:28 +0000357 DEBUG({
358 DebugTokenState(*State.NextToken);
359 });
360
Daniel Jaspere9de2602012-12-06 09:56:08 +0000361 // The first token has already been indented and thus consumed.
362 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000363
364 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000365 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000366 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
367 // Calculating the column is important for aligning trailing comments.
368 // FIXME: This does not seem to happen in conjunction with escaped
369 // newlines. If it does, fix!
370 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
371 State.NextToken->FormatTok.TokenLength;
372 State.NextToken = State.NextToken->Children.empty() ? NULL :
373 &State.NextToken->Children[0];
374 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000375 addTokenToState(false, false, State);
376 } else {
377 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
378 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000379 DEBUG({
380 if (Break < NoBreak)
381 llvm::errs() << "\n";
382 else
383 llvm::errs() << " ";
384 llvm::errs() << "<";
385 DebugPenalty(Break, Break < NoBreak);
386 llvm::errs() << "/";
387 DebugPenalty(NoBreak, !(Break < NoBreak));
388 llvm::errs() << "> ";
389 DebugTokenState(*State.NextToken);
390 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000391 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000392 if (State.NextToken != NULL &&
393 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
394 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000395 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000396 State.Stack.back().BreakAfterComma = true;
397 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000398 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000399 }
Manuel Klimek24998102013-01-16 14:55:28 +0000400 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000401 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000402 }
403
404private:
Manuel Klimek24998102013-01-16 14:55:28 +0000405 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
406 const Token &Tok = AnnotatedTok.FormatTok.Tok;
407 llvm::errs()
408 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
409 Tok.getLength());
410 llvm::errs();
411 }
412
413 void DebugPenalty(unsigned Penalty, bool Winner) {
414 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
415 if (Penalty == UINT_MAX)
416 llvm::errs() << "MAX";
417 else
418 llvm::errs() << Penalty;
419 llvm::errs().resetColor();
420 }
421
Daniel Jasper337816e2013-01-11 10:22:12 +0000422 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000423 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000424 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
425 FirstLessLess(0), BreakBeforeClosingBrace(false),
426 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000427
Daniel Jasperf7935112012-12-03 18:12:45 +0000428 /// \brief The position to which a specific parenthesis level needs to be
429 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000430 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000431
Daniel Jaspere9de2602012-12-06 09:56:08 +0000432 /// \brief The position of the last space on each level.
433 ///
434 /// Used e.g. to break like:
435 /// functionCall(Parameter, otherCall(
436 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000438
Daniel Jaspera836b902013-01-23 16:58:21 +0000439 /// \brief This is the column of the first token after an assignment.
440 unsigned AssignmentColumn;
441
Daniel Jaspere9de2602012-12-06 09:56:08 +0000442 /// \brief The position the first "<<" operator encountered on each level.
443 ///
444 /// Used to align "<<" operators. 0 if no such operator has been encountered
445 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000447
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000448 /// \brief Whether a newline needs to be inserted before the block's closing
449 /// brace.
450 ///
451 /// We only want to insert a newline before the closing brace if there also
452 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 bool BreakBeforeClosingBrace;
454
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000455 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000456 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000457
Daniel Jasper337816e2013-01-11 10:22:12 +0000458 bool operator<(const ParenState &Other) const {
459 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000460 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000461 if (LastSpace != Other.LastSpace)
462 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000463 if (AssignmentColumn != Other.AssignmentColumn)
464 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000465 if (FirstLessLess != Other.FirstLessLess)
466 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000467 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
468 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000469 if (BreakAfterComma != Other.BreakAfterComma)
470 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000471 if (HasMultiParameterLine != Other.HasMultiParameterLine)
472 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000473 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000474 }
475 };
476
477 /// \brief The current state when indenting a unwrapped line.
478 ///
479 /// As the indenting tries different combinations this is copied by value.
480 struct LineState {
481 /// \brief The number of used columns in the current line.
482 unsigned Column;
483
484 /// \brief The token that needs to be next formatted.
485 const AnnotatedToken *NextToken;
486
487 /// \brief The parenthesis level of the first token on the current line.
488 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000489
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000490 /// \brief The column of the first variable in a for-loop declaration.
491 ///
492 /// Used to align the second variable if necessary.
493 unsigned ForLoopVariablePos;
494
495 /// \brief \c true if this line contains a continued for-loop section.
496 bool LineContainsContinuedForLoopSection;
497
Daniel Jasper337816e2013-01-11 10:22:12 +0000498 /// \brief A stack keeping track of properties applying to parenthesis
499 /// levels.
500 std::vector<ParenState> Stack;
501
502 /// \brief Comparison operator to be able to used \c LineState in \c map.
503 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000504 if (Other.NextToken != NextToken)
505 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 if (Other.Column != Column)
507 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000508 if (Other.StartOfLineLevel != StartOfLineLevel)
509 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000510 if (Other.ForLoopVariablePos != ForLoopVariablePos)
511 return Other.ForLoopVariablePos < ForLoopVariablePos;
512 if (Other.LineContainsContinuedForLoopSection !=
513 LineContainsContinuedForLoopSection)
514 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000515 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000516 }
517 };
518
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000519 /// \brief Appends the next token to \p State and updates information
520 /// necessary for indentation.
521 ///
522 /// Puts the token on the current line if \p Newline is \c true and adds a
523 /// line break and necessary indentation otherwise.
524 ///
525 /// If \p DryRun is \c false, also creates and stores the required
526 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000527 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000528 const AnnotatedToken &Current = *State.NextToken;
529 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 assert(State.Stack.size());
531 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000532
533 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000534 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000535 if (Current.is(tok::r_brace)) {
536 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000537 } else if (Current.is(tok::string_literal) &&
538 Previous.is(tok::string_literal)) {
539 State.Column = State.Column - Previous.FormatTok.TokenLength;
540 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000541 State.Stack[ParenLevel].FirstLessLess != 0) {
542 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000543 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000544 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
545 Current.is(tok::period) || Previous.is(tok::question) ||
546 Previous.Type == TT_ConditionalExpr)) {
547 // Indent and extra 4 spaces after if we know the current expression is
548 // continued. Don't do that on the top level, as we already indent 4
549 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000550 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000551 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000552 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000553 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000554 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000555 } else if (Previous.Type == TT_BinaryOperator &&
556 State.Stack.back().AssignmentColumn != 0) {
557 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000558 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000560 }
561
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000562 // A line starting with a closing brace is assumed to be correct for the
563 // same level as before the opening brace.
564 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000565
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000566 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000567 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000568
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000569 if (!DryRun) {
570 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000571 Whitespaces.replaceWhitespace(Current, 1, State.Column,
572 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000573 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000574 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
575 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000576 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000577
Daniel Jasper337816e2013-01-11 10:22:12 +0000578 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000579 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000580 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000581 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000582 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
583 State.ForLoopVariablePos = State.Column -
584 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000585
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000586 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
587 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000588 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000589
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000591 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000592
Daniel Jasperbcab4302013-01-09 10:40:23 +0000593 // FIXME: Do we need to do this for assignments nested in other
594 // expressions?
595 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000596 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000597 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000598 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000599 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000600 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000601 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000602 if (Current.getPreviousNoneComment() != NULL &&
603 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000604 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000605 State.Stack[ParenLevel].HasMultiParameterLine = true;
606
Daniel Jaspere9de2602012-12-06 09:56:08 +0000607 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000608 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
609 // Treat the condition inside an if as if it was a second function
610 // parameter, i.e. let nested calls have an indent of 4.
611 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
612 else if (Spaces > 0 && ParenLevel != 0)
613 // Top-level spaces are exempt as that mostly leads to better results.
614 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000615 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000616
617 // If we break after an {, we should also break before the corresponding }.
618 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000619 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000620
Daniel Jaspere941b162013-01-23 10:08:28 +0000621 if (!Style.BinPackParameters && Newline) {
622 // If we are breaking after '(', '{', '<', this is not bin packing unless
623 // AllowAllParametersOnNextLine is false.
624 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
625 Previous.Type != TT_TemplateOpener) ||
626 !Style.AllowAllParametersOnNextLine)
627 State.Stack.back().BreakAfterComma = true;
628
629 // Any break on this level means that the parent level has been broken
630 // and we need to avoid bin packing there.
631 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
632 State.Stack[i].BreakAfterComma = true;
633 }
634 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000635
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000636 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000637 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000638
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000639 /// \brief Mark the next token as consumed in \p State and modify its stacks
640 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000641 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000642 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000643 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000644
Daniel Jasper337816e2013-01-11 10:22:12 +0000645 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
646 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000647
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000648 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000649 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000650 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
651 Current.is(tok::l_brace) ||
652 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000653 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000654 if (Current.is(tok::l_brace)) {
655 // FIXME: This does not work with nested static initializers.
656 // Implement a better handling for static initializers and similar
657 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000658 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000659 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000660 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000661 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000662 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000663 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000664 }
665
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000666 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000667 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000668 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
669 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
670 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000671 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000672 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000673
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000674 if (State.NextToken->Children.empty())
675 State.NextToken = NULL;
676 else
677 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000678
679 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000680 }
681
Nico Weber49cbc2c2013-01-07 15:15:29 +0000682 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000683 unsigned splitPenalty(const AnnotatedToken &Tok) {
684 const AnnotatedToken &Left = Tok;
685 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000686
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000687 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
688 return 50;
689 if (Left.is(tok::equal) && Right.is(tok::l_brace))
690 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000691 if (Left.is(tok::coloncolon))
692 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000693
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000694 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000695 if (RootToken.is(tok::kw_for) &&
696 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000697 return 20;
698
Daniel Jasper04468962013-01-18 10:56:38 +0000699 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000700 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000701
702 // In Objective-C method expressions, prefer breaking before "param:" over
703 // breaking after it.
704 if (isObjCSelectorName(Right))
705 return 0;
706 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
707 return 20;
708
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000709 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000710 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000711
Daniel Jasper399d24b2013-01-09 07:06:56 +0000712 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
713 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000714 prec::Level Level = getPrecedence(Left);
715
Daniel Jasperde5c2072012-12-24 00:13:23 +0000716 if (Level != prec::Unknown)
717 return Level;
718
Daniel Jasper04468962013-01-18 10:56:38 +0000719 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000720 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper04468962013-01-18 10:56:38 +0000721 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000722 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000723 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000724
Daniel Jasperf7935112012-12-03 18:12:45 +0000725 return 3;
726 }
727
Daniel Jasper2df93312013-01-09 10:16:05 +0000728 unsigned getColumnLimit() {
729 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
730 }
731
Daniel Jasperf7935112012-12-03 18:12:45 +0000732 /// \brief Calculate the number of lines needed to format the remaining part
733 /// of the unwrapped line.
734 ///
735 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000736 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 /// added after the previous token.
738 ///
739 /// \param StopAt is used for optimization. If we can determine that we'll
740 /// definitely need at least \p StopAt additional lines, we already know of a
741 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000742 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000743 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000744 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 return 0;
746
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000747 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000748 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000749 if (NewLine && !State.NextToken->CanBreakBefore &&
750 !(State.NextToken->is(tok::r_brace) &&
751 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000752 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000753 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000754 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000755 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000756 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000757 State.LineContainsContinuedForLoopSection)
758 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000759 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000760 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000761 State.Stack.back().BreakAfterComma)
762 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000763 // Trying to insert a parameter on a new line if there are already more than
764 // one parameter on the current line is bin packing.
765 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
766 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
767 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000768 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
769 (State.NextToken->Parent->ClosesTemplateDeclaration &&
770 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000771 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000772
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000773 unsigned CurrentPenalty = 0;
774 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000775 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000777 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000778 if (State.Stack.size() < State.StartOfLineLevel &&
779 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000780 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000781 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000782 }
783
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000784 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000785
Daniel Jasper2df93312013-01-09 10:16:05 +0000786 // Exceeding column limit is bad, assign penalty.
787 if (State.Column > getColumnLimit()) {
788 unsigned ExcessCharacters = State.Column - getColumnLimit();
789 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
790 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000791
Daniel Jasperf7935112012-12-03 18:12:45 +0000792 if (StopAt <= CurrentPenalty)
793 return UINT_MAX;
794 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000795 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000796 if (I != Memory.end()) {
797 // If this state has already been examined, we can safely return the
798 // previous result if we
799 // - have not hit the optimatization (and thus returned UINT_MAX) OR
800 // - are now computing for a smaller or equal StopAt.
801 unsigned SavedResult = I->second.first;
802 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000803 if (SavedResult != UINT_MAX)
804 return SavedResult + CurrentPenalty;
805 else if (StopAt <= SavedStopAt)
806 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000807 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000808
809 unsigned NoBreak = calcPenalty(State, false, StopAt);
810 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
811 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000812
813 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
814 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000815 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000816
817 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818 }
819
Daniel Jasperf7935112012-12-03 18:12:45 +0000820 FormatStyle Style;
821 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000822 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000823 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000824 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000825 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000826
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000827 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000828 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000829 StateMap Memory;
830
Daniel Jasperf7935112012-12-03 18:12:45 +0000831 OptimizationParameters Parameters;
832};
833
834/// \brief Determines extra information about the tokens comprising an
835/// \c UnwrappedLine.
836class TokenAnnotator {
837public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000838 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
839 AnnotatedLine &Line)
840 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000841
842 /// \brief A parser that gathers additional information about tokens.
843 ///
844 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
845 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
846 /// into template parameter lists.
847 class AnnotatingParser {
848 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000849 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000850 : CurrentToken(&RootToken), KeywordVirtualFound(false),
851 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000852
Nico Weber250fe712013-01-18 02:43:57 +0000853 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
854 struct ObjCSelectorRAII {
855 AnnotatingParser &P;
856 bool ColonWasObjCMethodExpr;
857
858 ObjCSelectorRAII(AnnotatingParser &P)
859 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
860
861 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
862
863 void markStart(AnnotatedToken &Left) {
864 P.ColonIsObjCMethodExpr = true;
865 Left.Type = TT_ObjCMethodExpr;
866 }
867
868 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
869 };
870
871
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000872 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000873 if (CurrentToken == NULL)
874 return false;
875 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 while (CurrentToken != NULL) {
877 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000878 Left->MatchingParen = CurrentToken;
879 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000880 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000881 next();
882 return true;
883 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000884 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
885 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000886 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000887 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
888 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000889 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000890 if (!consumeToken())
891 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000892 }
893 return false;
894 }
895
Nico Weber80a82762013-01-17 17:17:19 +0000896 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000897 if (CurrentToken == NULL)
898 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000899 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000900 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000901 if (CurrentToken->is(tok::caret)) {
902 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000903 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000904 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
905 // @selector( starts a selector.
906 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
907 MaybeSel->Parent->is(tok::at)) {
908 StartsObjCMethodExpr = true;
909 }
910 }
911
912 ObjCSelectorRAII objCSelector(*this);
913 if (StartsObjCMethodExpr)
914 objCSelector.markStart(*Left);
915
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000916 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000917 // LookForDecls is set when "if (" has been seen. Check for
918 // 'identifier' '*' 'identifier' followed by not '=' -- this
919 // '*' has to be a binary operator but determineStarAmpUsage() will
920 // categorize it as an unary operator, so set the right type here.
921 if (LookForDecls && !CurrentToken->Children.empty()) {
922 AnnotatedToken &Prev = *CurrentToken->Parent;
923 AnnotatedToken &Next = CurrentToken->Children[0];
924 if (Prev.Parent->is(tok::identifier) &&
925 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
926 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
927 Prev.Type = TT_BinaryOperator;
928 LookForDecls = false;
929 }
930 }
931
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000933 Left->MatchingParen = CurrentToken;
934 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000935
936 if (StartsObjCMethodExpr)
937 objCSelector.markEnd(*CurrentToken);
938
Daniel Jasperf7935112012-12-03 18:12:45 +0000939 next();
940 return true;
941 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000942 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000943 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000944 if (!consumeToken())
945 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000946 }
947 return false;
948 }
949
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000950 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000951 if (!CurrentToken)
952 return false;
953
954 // A '[' could be an index subscript (after an indentifier or after
955 // ')' or ']'), or it could be the start of an Objective-C method
956 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000957 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000958 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000959 !Left->Parent || Left->Parent->is(tok::colon) ||
960 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
961 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
962 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000963 true, true) > prec::Unknown;
964
Nico Weber250fe712013-01-18 02:43:57 +0000965 ObjCSelectorRAII objCSelector(*this);
966 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000967 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000968
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000969 while (CurrentToken != NULL) {
970 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000971 if (!CurrentToken->Children.empty() &&
972 CurrentToken->Children[0].is(tok::l_paren)) {
973 // An ObjC method call can't be followed by an open parenthesis.
974 // FIXME: Do we incorrectly label ":" with this?
975 StartsObjCMethodExpr = false;
976 Left->Type = TT_Unknown;
977 }
Nico Weber250fe712013-01-18 02:43:57 +0000978 if (StartsObjCMethodExpr)
979 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000980 Left->MatchingParen = CurrentToken;
981 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000982 next();
983 return true;
984 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000985 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000986 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000987 if (!consumeToken())
988 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000989 }
990 return false;
991 }
992
Daniel Jasper83a54d22013-01-10 09:26:47 +0000993 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000994 // Lines are fine to end with '{'.
995 if (CurrentToken == NULL)
996 return true;
997 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000998 while (CurrentToken != NULL) {
999 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001000 Left->MatchingParen = CurrentToken;
1001 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001002 next();
1003 return true;
1004 }
1005 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1006 return false;
1007 if (!consumeToken())
1008 return false;
1009 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001010 return true;
1011 }
1012
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001013 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001014 while (CurrentToken != NULL) {
1015 if (CurrentToken->is(tok::colon)) {
1016 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001017 next();
1018 return true;
1019 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001020 if (!consumeToken())
1021 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001022 }
1023 return false;
1024 }
1025
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001026 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001027 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1028 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001029 next();
1030 if (!parseAngle())
1031 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001032 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001033 return true;
1034 }
1035 return false;
1036 }
1037
Daniel Jasperc0880a92013-01-04 18:52:56 +00001038 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001039 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001040 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001041 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001042 case tok::plus:
1043 case tok::minus:
1044 // At the start of the line, +/- specific ObjectiveC method
1045 // declarations.
1046 if (Tok->Parent == NULL)
1047 Tok->Type = TT_ObjCMethodSpecifier;
1048 break;
Nico Webera7252d82013-01-12 06:18:40 +00001049 case tok::colon:
1050 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001051 if (Tok->Parent->is(tok::r_paren))
1052 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001053 if (ColonIsObjCMethodExpr)
1054 Tok->Type = TT_ObjCMethodExpr;
1055 break;
Nico Weber80a82762013-01-17 17:17:19 +00001056 case tok::kw_if:
1057 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001058 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001059 next();
1060 if (!parseParens(/*LookForDecls=*/true))
1061 return false;
1062 }
1063 break;
Nico Webera5510af2013-01-18 05:50:57 +00001064 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001065 if (!parseParens())
1066 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001067 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001068 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001069 if (!parseSquare())
1070 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001072 case tok::l_brace:
1073 if (!parseBrace())
1074 return false;
1075 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001077 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001079 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001080 Tok->Type = TT_BinaryOperator;
1081 CurrentToken = Tok;
1082 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 }
1084 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001085 case tok::r_paren:
1086 case tok::r_square:
1087 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001088 case tok::r_brace:
1089 // Lines can start with '}'.
1090 if (Tok->Parent != NULL)
1091 return false;
1092 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001094 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001095 break;
1096 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001097 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001098 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001099 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001100 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1101 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001102 next();
1103 }
1104 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001105 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1106 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001107 next();
1108 }
1109 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001110 break;
1111 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001112 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001113 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001114 case tok::kw_template:
1115 parseTemplateDeclaration();
1116 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001117 default:
1118 break;
1119 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001120 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001121 }
1122
Daniel Jasper050948a52012-12-21 17:58:39 +00001123 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001124 next();
1125 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1126 next();
1127 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001128 if (CurrentToken->isNot(tok::comment) ||
1129 !CurrentToken->Children.empty())
1130 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001131 next();
1132 }
1133 } else {
1134 while (CurrentToken != NULL) {
1135 next();
1136 }
1137 }
1138 }
1139
1140 void parseWarningOrError() {
1141 next();
1142 // We still want to format the whitespace left of the first token of the
1143 // warning or error.
1144 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001145 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001146 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001147 next();
1148 }
1149 }
1150
1151 void parsePreprocessorDirective() {
1152 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001153 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001154 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001155 // Hashes in the middle of a line can lead to any strange token
1156 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001157 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001158 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001159 switch (
1160 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001161 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001162 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001163 parseIncludeDirective();
1164 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001165 case tok::pp_error:
1166 case tok::pp_warning:
1167 parseWarningOrError();
1168 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001169 default:
1170 break;
1171 }
1172 }
1173
Daniel Jasperda16db32013-01-07 10:48:50 +00001174 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001175 int PeriodsAndArrows = 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001176 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001177 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001178 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001179 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001180 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001181
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001182 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001183 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001184 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1185 ++PeriodsAndArrows;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001186 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001187 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001188 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001189 if (KeywordVirtualFound)
1190 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001191
1192 // Assume a builder-type call if there are 2 or more "." and "->".
1193 if (PeriodsAndArrows >= 2)
1194 return LT_BuilderTypeCall;
1195
Daniel Jasperda16db32013-01-07 10:48:50 +00001196 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001197 }
1198
1199 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001200 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1201 CurrentToken = &CurrentToken->Children[0];
1202 else
1203 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001204 }
1205
1206 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001207 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001208 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001209 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001210 };
1211
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001212 void calculateExtraInformation(AnnotatedToken &Current) {
1213 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1214
Manuel Klimek52b15152013-01-09 15:25:02 +00001215 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001216 Current.MustBreakBefore = true;
1217 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001218 if (Current.Type == TT_LineComment) {
1219 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001220 } else if ((Current.Parent->is(tok::comment) &&
1221 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001222 (Current.is(tok::string_literal) &&
1223 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001224 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001225 } else {
1226 Current.MustBreakBefore = false;
1227 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001228 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001229 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001230 if (Current.MustBreakBefore)
1231 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1232 else
1233 Current.TotalLength = Current.Parent->TotalLength +
1234 Current.FormatTok.TokenLength +
1235 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001236 if (!Current.Children.empty())
1237 calculateExtraInformation(Current.Children[0]);
1238 }
1239
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001240 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001241 AnnotatingParser Parser(Line.First);
1242 Line.Type = Parser.parseLine();
1243 if (Line.Type == LT_Invalid)
1244 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245
Daniel Jasper5b49f472013-01-23 12:10:53 +00001246 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001247
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001248 if (Line.First.Type == TT_ObjCMethodSpecifier)
1249 Line.Type = LT_ObjCMethodDecl;
1250 else if (Line.First.Type == TT_ObjCDecl)
1251 Line.Type = LT_ObjCDecl;
1252 else if (Line.First.Type == TT_ObjCProperty)
1253 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001254
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001255 Line.First.SpaceRequiredBefore = true;
1256 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1257 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001258
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001259 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001260 if (!Line.First.Children.empty())
1261 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001262 }
1263
1264private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001265 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1266 if (getPrecedence(Current) == prec::Assignment) {
1267 IsExpression = true;
1268 AnnotatedToken *Previous = Current.Parent;
1269 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001270 if (Previous->Type == TT_BinaryOperator &&
1271 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001272 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001273 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001274 Previous = Previous->Parent;
1275 }
1276 }
1277 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001278 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1279 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001280 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001281
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001282 if (Current.Type == TT_Unknown) {
1283 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001284 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001285 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1286 Current.is(tok::caret)) {
1287 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001288 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1289 Current.Type = determineIncrementUsage(Current);
1290 } else if (Current.is(tok::exclaim)) {
1291 Current.Type = TT_UnaryOperator;
1292 } else if (isBinaryOperator(Current)) {
1293 Current.Type = TT_BinaryOperator;
1294 } else if (Current.is(tok::comment)) {
1295 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1296 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001297 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001298 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001299 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001300 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001301 } else if (Current.is(tok::r_paren) &&
1302 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001303 Current.Parent->Type == TT_TemplateCloser) &&
1304 (Current.Children.empty() ||
1305 (Current.Children[0].isNot(tok::equal) &&
1306 Current.Children[0].isNot(tok::semi) &&
1307 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001308 // FIXME: We need to get smarter and understand more cases of casts.
1309 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001310 } else if (Current.is(tok::at) && Current.Children.size()) {
1311 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1312 case tok::objc_interface:
1313 case tok::objc_implementation:
1314 case tok::objc_protocol:
1315 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001316 break;
1317 case tok::objc_property:
1318 Current.Type = TT_ObjCProperty;
1319 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001320 default:
1321 break;
1322 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001323 }
1324 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001325
1326 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001327 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001328 }
1329
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001330 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001331 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001332 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001333 }
1334
Daniel Jasper71945272013-01-15 14:27:39 +00001335 /// \brief Returns the previous token ignoring comments.
1336 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1337 const AnnotatedToken *PrevToken = Tok.Parent;
1338 while (PrevToken != NULL && PrevToken->is(tok::comment))
1339 PrevToken = PrevToken->Parent;
1340 return PrevToken;
1341 }
1342
1343 /// \brief Returns the next token ignoring comments.
1344 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1345 if (Tok.Children.empty())
1346 return NULL;
1347 const AnnotatedToken *NextToken = &Tok.Children[0];
1348 while (NextToken->is(tok::comment)) {
1349 if (NextToken->Children.empty())
1350 return NULL;
1351 NextToken = &NextToken->Children[0];
1352 }
1353 return NextToken;
1354 }
1355
1356 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001357 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1358 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001359 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1360 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001361 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001362
1363 const AnnotatedToken *NextToken = getNextToken(Tok);
1364 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001365 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001366
Daniel Jasper0b820602013-01-22 11:46:26 +00001367 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1368 return TT_PointerOrReference;
1369
Daniel Jasper71945272013-01-15 14:27:39 +00001370 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1371 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1372 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1373 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001374 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001375 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001376
Daniel Jasper71945272013-01-15 14:27:39 +00001377 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1378 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1379 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1380 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1381 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1382 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1383 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001384 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001385
Daniel Jasper71945272013-01-15 14:27:39 +00001386 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1387 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001388 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001389
Daniel Jasper426702d2012-12-05 07:51:39 +00001390 // It is very unlikely that we are going to find a pointer or reference type
1391 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001392 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001393 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001394
Daniel Jasperda16db32013-01-07 10:48:50 +00001395 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001396 }
1397
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001398 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001399 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1400 if (PrevToken == NULL)
1401 return TT_UnaryOperator;
1402
Daniel Jasper8dd40472012-12-21 09:41:31 +00001403 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001404 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1405 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1406 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1407 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1408 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001409 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001410
1411 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001412 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001413 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001414
1415 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001416 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001417 }
1418
1419 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001420 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001421 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1422 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001423 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001424 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1425 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001426 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001427
Daniel Jasperda16db32013-01-07 10:48:50 +00001428 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001429 }
1430
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001431 bool spaceRequiredBetween(const AnnotatedToken &Left,
1432 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001433 if (Right.is(tok::hashhash))
1434 return Left.is(tok::hash);
1435 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1436 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001437 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1438 return false;
Nico Webera6087752013-01-10 20:12:55 +00001439 if (Right.is(tok::less) &&
1440 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001441 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001442 return true;
1443 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1444 return false;
1445 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1446 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001447 if (Left.is(tok::at) &&
1448 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1449 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001450 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1451 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001452 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001453 if (Left.is(tok::coloncolon))
1454 return false;
1455 if (Right.is(tok::coloncolon))
1456 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001457 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1458 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001459 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001460 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001461 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1462 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001463 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001464 return Right.FormatTok.Tok.isLiteral() ||
1465 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001466 if (Right.is(tok::star) && Left.is(tok::l_paren))
1467 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001468 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1469 return false;
1470 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001471 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001472 if (Left.is(tok::period) || Right.is(tok::period))
1473 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001474 if (Left.is(tok::colon))
1475 return Left.Type != TT_ObjCMethodExpr;
1476 if (Right.is(tok::colon))
1477 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001478 if (Left.is(tok::l_paren))
1479 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001480 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001481 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001482 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001483 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001484 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1485 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001486 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001487 if (Left.is(tok::at) &&
1488 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001489 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001490 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1491 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001492 return true;
1493 }
1494
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001495 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001496 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001497 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1498 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001499 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001500 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001501 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001502 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001503 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001504 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001505 // Don't space between ')' and <id>
1506 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001507 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001508 // Don't space between ':' and '('
1509 return false;
1510 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001511 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001512 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1513 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001514
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001515 if (Tok.Parent->is(tok::comma))
1516 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001517 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001518 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001519 if (Tok.Type == TT_OverloadedOperator)
1520 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001521 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001522 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001523 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001524 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001525 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001526 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001527 if (Tok.Parent->Type == TT_UnaryOperator ||
1528 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001529 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001530 if (Tok.Type == TT_UnaryOperator)
1531 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001532 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1533 (Tok.Parent->isNot(tok::colon) ||
1534 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001535 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1536 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001537 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1538 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001539 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001540 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001541 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001542 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001543 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001544 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001545 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001546 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001547 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001548 }
1549
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001550 bool canBreakBefore(const AnnotatedToken &Right) {
1551 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001553 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1554 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001555 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001556 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1557 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001558 // Don't break this identifier as ':' or identifier
1559 // before it will break.
1560 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001561 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1562 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001563 // Don't break at ':' if identifier before it can beak.
1564 return false;
1565 }
Nico Webera7252d82013-01-12 06:18:40 +00001566 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1567 return false;
1568 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1569 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001570 if (isObjCSelectorName(Right))
1571 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001572 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001573 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001575 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001576 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001577 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001578 return false;
1579
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001580 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001581 // We rely on MustBreakBefore being set correctly here as we should not
1582 // change the "binding" behavior of a comment.
1583 return false;
1584
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001585 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1586 // unless it is follow by ';', '{' or '='.
1587 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1588 Left.Parent->is(tok::r_paren))
1589 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1590 Right.isNot(tok::equal);
1591
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001592 // We only break before r_brace if there was a corresponding break before
1593 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1594 if (Right.is(tok::r_brace))
1595 return false;
1596
Daniel Jasper71945272013-01-15 14:27:39 +00001597 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001598 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001599 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1600 Left.is(tok::comma) || Right.is(tok::lessless) ||
1601 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001602 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1603 Left.is(tok::semi) || Left.is(tok::l_brace) ||
1604 Left.is(tok::question) || Left.Type == TT_ConditionalExpr ||
1605 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1606 Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001607 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001608 }
1609
Daniel Jasperf7935112012-12-03 18:12:45 +00001610 FormatStyle Style;
1611 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001612 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001613 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001614};
1615
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001616class LexerBasedFormatTokenSource : public FormatTokenSource {
1617public:
1618 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001619 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001620 IdentTable(Lex.getLangOpts()) {
1621 Lex.SetKeepWhitespaceMode(true);
1622 }
1623
1624 virtual FormatToken getNextToken() {
1625 if (GreaterStashed) {
1626 FormatTok.NewlinesBefore = 0;
1627 FormatTok.WhiteSpaceStart =
1628 FormatTok.Tok.getLocation().getLocWithOffset(1);
1629 FormatTok.WhiteSpaceLength = 0;
1630 GreaterStashed = false;
1631 return FormatTok;
1632 }
1633
1634 FormatTok = FormatToken();
1635 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001636 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001637 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001638 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1639 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001640
1641 // Consume and record whitespace until we find a significant token.
1642 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001643 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001644 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1645 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001646 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1647
1648 if (FormatTok.Tok.is(tok::eof))
1649 return FormatTok;
1650 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001651 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001652 }
Manuel Klimekef920692013-01-07 07:56:50 +00001653
1654 // Now FormatTok is the next non-whitespace token.
1655 FormatTok.TokenLength = Text.size();
1656
Manuel Klimek1abf7892013-01-04 23:34:14 +00001657 // In case the token starts with escaped newlines, we want to
1658 // take them into account as whitespace - this pattern is quite frequent
1659 // in macro definitions.
1660 // FIXME: What do we want to do with other escaped spaces, and escaped
1661 // spaces or newlines in the middle of tokens?
1662 // FIXME: Add a more explicit test.
1663 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001664 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001665 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001666 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001667 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001668 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001669 }
1670
1671 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001672 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001673 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001674 FormatTok.Tok.setKind(Info.getTokenID());
1675 }
1676
1677 if (FormatTok.Tok.is(tok::greatergreater)) {
1678 FormatTok.Tok.setKind(tok::greater);
1679 GreaterStashed = true;
1680 }
1681
1682 return FormatTok;
1683 }
1684
1685private:
1686 FormatToken FormatTok;
1687 bool GreaterStashed;
1688 Lexer &Lex;
1689 SourceManager &SourceMgr;
1690 IdentifierTable IdentTable;
1691
1692 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001693 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001694 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1695 Tok.getLength());
1696 }
1697};
1698
Daniel Jasperf7935112012-12-03 18:12:45 +00001699class Formatter : public UnwrappedLineConsumer {
1700public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001701 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1702 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001703 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001704 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001705 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001706
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001707 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001708
Daniel Jasperf7935112012-12-03 18:12:45 +00001709 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001710 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001711 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001712 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001713 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001714 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1715 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1716 Annotator.annotate();
1717 }
1718 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1719 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001720 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001721 const AnnotatedLine &TheLine = *I;
1722 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1723 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1724 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001725 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001726 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001727 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001728 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001729 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001730 PreviousEndOfLineColumn = Formatter.format();
1731 } else {
1732 // If we did not reformat this unwrapped line, the column at the end of
1733 // the last token is unchanged - thus, we can calculate the end of the
1734 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001735 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001736 SourceMgr.getSpellingColumnNumber(
1737 TheLine.Last->FormatTok.Tok.getLocation()) +
1738 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1739 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001740 1;
1741 }
1742 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001743 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001744 }
1745
1746private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001747 /// \brief Tries to merge lines into one.
1748 ///
1749 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1750 /// if possible; note that \c I will be incremented when lines are merged.
1751 ///
1752 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001753 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001754 std::vector<AnnotatedLine>::iterator &I,
1755 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001756 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1757
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001758 // We can never merge stuff if there are trailing line comments.
1759 if (I->Last->Type == TT_LineComment)
1760 return;
1761
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001762 // Check whether the UnwrappedLine can be put onto a single line. If
1763 // so, this is bound to be the optimal solution (by definition) and we
1764 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001765 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001766 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001767 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001768
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001769 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001770 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001771
Daniel Jasper25837aa2013-01-14 14:14:23 +00001772 if (I->Last->is(tok::l_brace)) {
1773 tryMergeSimpleBlock(I, E, Limit);
1774 } else if (I->First.is(tok::kw_if)) {
1775 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001776 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1777 I->First.FormatTok.IsFirst)) {
1778 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001779 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001780 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001781 }
1782
Daniel Jasper39825ea2013-01-14 15:40:57 +00001783 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1784 std::vector<AnnotatedLine>::iterator E,
1785 unsigned Limit) {
1786 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001787 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1788 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001789 if (I + 2 != E && (I + 2)->InPPDirective &&
1790 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1791 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001792 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001793 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001794 join(Line, *(++I));
1795 }
1796
Daniel Jasper25837aa2013-01-14 14:14:23 +00001797 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1798 std::vector<AnnotatedLine>::iterator E,
1799 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001800 if (!Style.AllowShortIfStatementsOnASingleLine)
1801 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001802 if ((I + 1)->InPPDirective != I->InPPDirective ||
1803 ((I + 1)->InPPDirective &&
1804 (I + 1)->First.FormatTok.HasUnescapedNewline))
1805 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001806 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001807 if (Line.Last->isNot(tok::r_paren))
1808 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001809 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001810 return;
1811 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1812 return;
1813 // Only inline simple if's (no nested if or else).
1814 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1815 return;
1816 join(Line, *(++I));
1817 }
1818
1819 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1820 std::vector<AnnotatedLine>::iterator E,
1821 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001822 // First, check that the current line allows merging. This is the case if
1823 // we're not in a control flow statement and the last token is an opening
1824 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001825 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001826 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001827 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1828 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1829 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1830 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001831 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001832 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1833 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001834 if (!AllowedTokens)
1835 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001836
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001837 AnnotatedToken *Tok = &(I + 1)->First;
1838 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1839 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1840 Tok->SpaceRequiredBefore = false;
1841 join(Line, *(I + 1));
1842 I += 1;
1843 } else {
1844 // Check that we still have three lines and they fit into the limit.
1845 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1846 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001847 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001848
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001849 // Second, check that the next line does not contain any braces - if it
1850 // does, readability declines when putting it into a single line.
1851 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1852 return;
1853 do {
1854 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1855 return;
1856 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1857 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001858
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001859 // Last, check that the third line contains a single closing brace.
1860 Tok = &(I + 2)->First;
1861 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1862 Tok->MustBreakBefore)
1863 return;
1864
1865 join(Line, *(I + 1));
1866 join(Line, *(I + 2));
1867 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001868 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001869 }
1870
1871 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1872 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001873 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1874 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001875 }
1876
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001877 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1878 A.Last->Children.push_back(B.First);
1879 while (!A.Last->Children.empty()) {
1880 A.Last->Children[0].Parent = A.Last;
1881 A.Last = &A.Last->Children[0];
1882 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001883 }
1884
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001885 bool touchesRanges(const AnnotatedLine &TheLine) {
1886 const FormatToken *First = &TheLine.First.FormatTok;
1887 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001888 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001889 First->Tok.getLocation(),
1890 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001891 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001892 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1893 Ranges[i].getBegin()) &&
1894 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1895 LineRange.getBegin()))
1896 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001897 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001898 return false;
1899 }
1900
1901 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001902 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001903 }
1904
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001905 /// \brief Add a new line and the required indent before the first Token
1906 /// of the \c UnwrappedLine if there was no structural parsing error.
1907 /// Returns the indent level of the \c UnwrappedLine.
1908 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1909 bool InPPDirective,
1910 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001911 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001912 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1913 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1914
1915 unsigned Newlines = std::min(Tok.NewlinesBefore,
1916 Style.MaxEmptyLinesToKeep + 1);
1917 if (Newlines == 0 && !Tok.IsFirst)
1918 Newlines = 1;
1919 unsigned Indent = Level * 2;
1920
1921 bool IsAccessModifier = false;
1922 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1923 RootToken.is(tok::kw_private))
1924 IsAccessModifier = true;
1925 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1926 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1927 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1928 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1929 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1930 IsAccessModifier = true;
1931
1932 if (IsAccessModifier &&
1933 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1934 Indent += Style.AccessModifierOffset;
1935 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001936 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001937 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001938 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1939 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001940 }
1941 return Indent;
1942 }
1943
Alexander Kornienko116ba682013-01-14 11:34:14 +00001944 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001945 FormatStyle Style;
1946 Lexer &Lex;
1947 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001948 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001949 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001950 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001951 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001952};
1953
1954tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1955 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001956 std::vector<CharSourceRange> Ranges,
1957 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001958 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001959 OwningPtr<DiagnosticConsumer> DiagPrinter;
1960 if (DiagClient == 0) {
1961 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1962 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1963 DiagClient = DiagPrinter.get();
1964 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001965 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001966 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001967 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001968 Diagnostics.setSourceManager(&SourceMgr);
1969 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001970 return formatter.format();
1971}
1972
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001973LangOptions getFormattingLangOpts() {
1974 LangOptions LangOpts;
1975 LangOpts.CPlusPlus = 1;
1976 LangOpts.CPlusPlus11 = 1;
1977 LangOpts.Bool = 1;
1978 LangOpts.ObjC1 = 1;
1979 LangOpts.ObjC2 = 1;
1980 return LangOpts;
1981}
1982
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001983} // namespace format
1984} // namespace clang