blob: 99b2d545c2a92014ecb03f82b284d6946b1ed226 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000063 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000064 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000069};
70
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000073 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL),
77 ParameterCount(1), Parent(NULL) {
78 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000079
Daniel Jasper25837aa2013-01-14 14:14:23 +000080 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
81 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
82
Daniel Jasper7c85fde2013-01-08 14:56:18 +000083 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
84 return FormatTok.Tok.isObjCAtKeyword(Kind);
85 }
86
87 FormatToken FormatTok;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 TokenType Type;
90
Daniel Jasperf7935112012-12-03 18:12:45 +000091 bool SpaceRequiredBefore;
92 bool CanBreakBefore;
93 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000094
95 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000096
Daniel Jasper9278eb92013-01-16 14:59:02 +000097 AnnotatedToken *MatchingParen;
98
Daniel Jasper7b5773e92013-01-28 07:35:34 +000099 /// \brief Number of parameters, if this is "(", "[" or "<".
100 ///
101 /// This is initialized to 1 as we don't need to distinguish functions with
102 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
103 /// the number of commas.
104 unsigned ParameterCount;
105
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000106 /// \brief The total length of the line up to and including this token.
107 unsigned TotalLength;
108
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000109 std::vector<AnnotatedToken> Children;
110 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000111
112 const AnnotatedToken *getPreviousNoneComment() const {
113 AnnotatedToken *Tok = Parent;
114 while (Tok != NULL && Tok->is(tok::comment))
115 Tok = Tok->Parent;
116 return Tok;
117 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000118};
119
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000120class AnnotatedLine {
121public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000122 AnnotatedLine(const UnwrappedLine &Line)
123 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000124 InPPDirective(Line.InPPDirective),
125 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000126 assert(!Line.Tokens.empty());
127 AnnotatedToken *Current = &First;
128 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
129 E = Line.Tokens.end();
130 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000132 Current->Children[0].Parent = Current;
133 Current = &Current->Children[0];
134 }
135 Last = Current;
136 }
137 AnnotatedLine(const AnnotatedLine &Other)
138 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000139 InPPDirective(Other.InPPDirective),
140 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000141 Last = &First;
142 while (!Last->Children.empty()) {
143 Last->Children[0].Parent = Last;
144 Last = &Last->Children[0];
145 }
146 }
147
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000148 AnnotatedToken First;
149 AnnotatedToken *Last;
150
151 LineType Type;
152 unsigned Level;
153 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000154 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000155};
156
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000157static prec::Level getPrecedence(const AnnotatedToken &Tok) {
158 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000159}
160
Daniel Jasperf7935112012-12-03 18:12:45 +0000161FormatStyle getLLVMStyle() {
162 FormatStyle LLVMStyle;
163 LLVMStyle.ColumnLimit = 80;
164 LLVMStyle.MaxEmptyLinesToKeep = 1;
165 LLVMStyle.PointerAndReferenceBindToType = false;
166 LLVMStyle.AccessModifierOffset = -2;
167 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000168 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000169 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000170 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000171 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000172 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000173 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000174 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 return LLVMStyle;
176}
177
178FormatStyle getGoogleStyle() {
179 FormatStyle GoogleStyle;
180 GoogleStyle.ColumnLimit = 80;
181 GoogleStyle.MaxEmptyLinesToKeep = 1;
182 GoogleStyle.PointerAndReferenceBindToType = true;
183 GoogleStyle.AccessModifierOffset = -1;
184 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000185 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000186 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000187 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000188 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000189 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000190 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000191 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000192 return GoogleStyle;
193}
194
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000195FormatStyle getChromiumStyle() {
196 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000197 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000198 return ChromiumStyle;
199}
200
Daniel Jasperf7935112012-12-03 18:12:45 +0000201struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000202 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000203 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000204 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000205};
206
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000207/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000208///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000209/// This includes special handling for certain constructs, e.g. the alignment of
210/// trailing line comments.
211class WhitespaceManager {
212public:
213 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
214
215 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
216 /// each \c AnnotatedToken.
217 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
218 unsigned Spaces, unsigned WhitespaceStartColumn,
219 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000220 // 2+ newlines mean an empty line separating logic scopes.
221 if (NewLines >= 2)
222 alignComments();
223
224 // Align line comments if they are trailing or if they continue other
225 // trailing comments.
226 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000227 (Tok.Parent != NULL || !Comments.empty())) {
228 if (Style.ColumnLimit >=
229 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
230 Comments.push_back(StoredComment());
231 Comments.back().Tok = Tok.FormatTok;
232 Comments.back().Spaces = Spaces;
233 Comments.back().NewLines = NewLines;
234 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
235 Comments.back().MaxColumn = Style.ColumnLimit -
236 Spaces - Tok.FormatTok.TokenLength;
237 return;
238 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000239 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000240
241 // If this line does not have a trailing comment, align the stored comments.
242 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
243 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000244 storeReplacement(Tok.FormatTok,
245 std::string(NewLines, '\n') + std::string(Spaces, ' '));
246 }
247
248 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
249 /// backslashes to escape newlines inside a preprocessor directive.
250 ///
251 /// This function and \c replaceWhitespace have the same behavior if
252 /// \c Newlines == 0.
253 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
254 unsigned Spaces, unsigned WhitespaceStartColumn,
255 const FormatStyle &Style) {
256 std::string NewLineText;
257 if (NewLines > 0) {
258 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
259 WhitespaceStartColumn);
260 for (unsigned i = 0; i < NewLines; ++i) {
261 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
262 NewLineText += "\\\n";
263 Offset = 0;
264 }
265 }
266 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
267 }
268
269 /// \brief Returns all the \c Replacements created during formatting.
270 const tooling::Replacements &generateReplacements() {
271 alignComments();
272 return Replaces;
273 }
274
275private:
276 /// \brief Structure to store a comment for later layout and alignment.
277 struct StoredComment {
278 FormatToken Tok;
279 unsigned MinColumn;
280 unsigned MaxColumn;
281 unsigned NewLines;
282 unsigned Spaces;
283 };
284 SmallVector<StoredComment, 16> Comments;
285 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
286
287 /// \brief Try to align all stashed comments.
288 void alignComments() {
289 unsigned MinColumn = 0;
290 unsigned MaxColumn = UINT_MAX;
291 comment_iterator Start = Comments.begin();
292 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
293 ++I) {
294 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
295 alignComments(Start, I, MinColumn);
296 MinColumn = I->MinColumn;
297 MaxColumn = I->MaxColumn;
298 Start = I;
299 } else {
300 MinColumn = std::max(MinColumn, I->MinColumn);
301 MaxColumn = std::min(MaxColumn, I->MaxColumn);
302 }
303 }
304 alignComments(Start, Comments.end(), MinColumn);
305 Comments.clear();
306 }
307
308 /// \brief Put all the comments between \p I and \p E into \p Column.
309 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
310 while (I != E) {
311 unsigned Spaces = I->Spaces + Column - I->MinColumn;
312 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
313 std::string(Spaces, ' '));
314 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000315 }
316 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000317
318 /// \brief Stores \p Text as the replacement for the whitespace in front of
319 /// \p Tok.
320 void storeReplacement(const FormatToken &Tok, const std::string Text) {
321 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
322 Tok.WhiteSpaceLength, Text));
323 }
324
325 SourceManager &SourceMgr;
326 tooling::Replacements Replaces;
327};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000328
Nico Weberc9d73612013-01-12 22:48:47 +0000329/// \brief Returns if a token is an Objective-C selector name.
330///
Nico Weber92c05392013-01-12 22:51:13 +0000331/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000332static bool isObjCSelectorName(const AnnotatedToken &Tok) {
333 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
334 Tok.Children[0].is(tok::colon) &&
335 Tok.Children[0].Type == TT_ObjCMethodExpr;
336}
337
Daniel Jasperf7935112012-12-03 18:12:45 +0000338class UnwrappedLineFormatter {
339public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000340 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000341 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000342 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000343 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000344 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000345 FirstIndent(FirstIndent), RootToken(RootToken),
346 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000347 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000348 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000349 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 }
351
Manuel Klimek1abf7892013-01-04 23:34:14 +0000352 /// \brief Formats an \c UnwrappedLine.
353 ///
354 /// \returns The column after the last token in the last line of the
355 /// \c UnwrappedLine.
356 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000357 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000358 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000359 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000360 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000361 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000362 State.ForLoopVariablePos = 0;
363 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000364 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000365
Manuel Klimek24998102013-01-16 14:55:28 +0000366 DEBUG({
367 DebugTokenState(*State.NextToken);
368 });
369
Daniel Jaspere9de2602012-12-06 09:56:08 +0000370 // The first token has already been indented and thus consumed.
371 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000372
373 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000374 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000375 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
376 // Calculating the column is important for aligning trailing comments.
377 // FIXME: This does not seem to happen in conjunction with escaped
378 // newlines. If it does, fix!
379 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
380 State.NextToken->FormatTok.TokenLength;
381 State.NextToken = State.NextToken->Children.empty() ? NULL :
382 &State.NextToken->Children[0];
383 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000384 addTokenToState(false, false, State);
385 } else {
386 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
387 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000388 DEBUG({
389 if (Break < NoBreak)
390 llvm::errs() << "\n";
391 else
392 llvm::errs() << " ";
393 llvm::errs() << "<";
394 DebugPenalty(Break, Break < NoBreak);
395 llvm::errs() << "/";
396 DebugPenalty(NoBreak, !(Break < NoBreak));
397 llvm::errs() << "> ";
398 DebugTokenState(*State.NextToken);
399 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000400 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000401 if (State.NextToken != NULL &&
402 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
403 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000404 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000405 State.Stack.back().BreakAfterComma = true;
406 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000407 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000408 }
Manuel Klimek24998102013-01-16 14:55:28 +0000409 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000410 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
412
413private:
Manuel Klimek24998102013-01-16 14:55:28 +0000414 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
415 const Token &Tok = AnnotatedTok.FormatTok.Tok;
416 llvm::errs()
417 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
418 Tok.getLength());
419 llvm::errs();
420 }
421
422 void DebugPenalty(unsigned Penalty, bool Winner) {
423 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
424 if (Penalty == UINT_MAX)
425 llvm::errs() << "MAX";
426 else
427 llvm::errs() << Penalty;
428 llvm::errs().resetColor();
429 }
430
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000432 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000433 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
434 FirstLessLess(0), BreakBeforeClosingBrace(false),
435 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000436
Daniel Jasperf7935112012-12-03 18:12:45 +0000437 /// \brief The position to which a specific parenthesis level needs to be
438 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000439 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000440
Daniel Jaspere9de2602012-12-06 09:56:08 +0000441 /// \brief The position of the last space on each level.
442 ///
443 /// Used e.g. to break like:
444 /// functionCall(Parameter, otherCall(
445 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000447
Daniel Jaspera836b902013-01-23 16:58:21 +0000448 /// \brief This is the column of the first token after an assignment.
449 unsigned AssignmentColumn;
450
Daniel Jaspere9de2602012-12-06 09:56:08 +0000451 /// \brief The position the first "<<" operator encountered on each level.
452 ///
453 /// Used to align "<<" operators. 0 if no such operator has been encountered
454 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000455 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000456
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000457 /// \brief Whether a newline needs to be inserted before the block's closing
458 /// brace.
459 ///
460 /// We only want to insert a newline before the closing brace if there also
461 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000462 bool BreakBeforeClosingBrace;
463
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000464 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000465 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000466
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 bool operator<(const ParenState &Other) const {
468 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000469 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000470 if (LastSpace != Other.LastSpace)
471 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000472 if (AssignmentColumn != Other.AssignmentColumn)
473 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000474 if (FirstLessLess != Other.FirstLessLess)
475 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000476 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
477 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000478 if (BreakAfterComma != Other.BreakAfterComma)
479 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000480 if (HasMultiParameterLine != Other.HasMultiParameterLine)
481 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000482 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000483 }
484 };
485
486 /// \brief The current state when indenting a unwrapped line.
487 ///
488 /// As the indenting tries different combinations this is copied by value.
489 struct LineState {
490 /// \brief The number of used columns in the current line.
491 unsigned Column;
492
493 /// \brief The token that needs to be next formatted.
494 const AnnotatedToken *NextToken;
495
496 /// \brief The parenthesis level of the first token on the current line.
497 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000498
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 /// \brief The column of the first variable in a for-loop declaration.
500 ///
501 /// Used to align the second variable if necessary.
502 unsigned ForLoopVariablePos;
503
504 /// \brief \c true if this line contains a continued for-loop section.
505 bool LineContainsContinuedForLoopSection;
506
Daniel Jasper337816e2013-01-11 10:22:12 +0000507 /// \brief A stack keeping track of properties applying to parenthesis
508 /// levels.
509 std::vector<ParenState> Stack;
510
511 /// \brief Comparison operator to be able to used \c LineState in \c map.
512 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000513 if (Other.NextToken != NextToken)
514 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000515 if (Other.Column != Column)
516 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000517 if (Other.StartOfLineLevel != StartOfLineLevel)
518 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000519 if (Other.ForLoopVariablePos != ForLoopVariablePos)
520 return Other.ForLoopVariablePos < ForLoopVariablePos;
521 if (Other.LineContainsContinuedForLoopSection !=
522 LineContainsContinuedForLoopSection)
523 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000524 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 }
526 };
527
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000528 /// \brief Appends the next token to \p State and updates information
529 /// necessary for indentation.
530 ///
531 /// Puts the token on the current line if \p Newline is \c true and adds a
532 /// line break and necessary indentation otherwise.
533 ///
534 /// If \p DryRun is \c false, also creates and stores the required
535 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000536 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000537 const AnnotatedToken &Current = *State.NextToken;
538 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 assert(State.Stack.size());
540 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000541
542 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000543 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000544 if (Current.is(tok::r_brace)) {
545 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000546 } else if (Current.is(tok::string_literal) &&
547 Previous.is(tok::string_literal)) {
548 State.Column = State.Column - Previous.FormatTok.TokenLength;
549 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000550 State.Stack[ParenLevel].FirstLessLess != 0) {
551 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000552 } else if (ParenLevel != 0 &&
Daniel Jasper4ad42352013-01-28 07:43:15 +0000553 (Previous.is(tok::equal) || Previous.is(tok::coloncolon) ||
554 Previous.is(tok::question) ||
555 Previous.Type == TT_ConditionalExpr ||
556 Current.is(tok::period) || Current.is(tok::arrow))) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000557 // Indent and extra 4 spaces after if we know the current expression is
558 // continued. Don't do that on the top level, as we already indent 4
559 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000560 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000561 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000562 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000563 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000565 } else if (Previous.Type == TT_BinaryOperator &&
566 State.Stack.back().AssignmentColumn != 0) {
567 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000568 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000569 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000570 }
571
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000572 // A line starting with a closing brace is assumed to be correct for the
573 // same level as before the opening brace.
574 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000575
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000576 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000577 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000578
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000579 if (!DryRun) {
580 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000581 Whitespaces.replaceWhitespace(Current, 1, State.Column,
582 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000583 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000584 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
585 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000586 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000587
Daniel Jasper337816e2013-01-11 10:22:12 +0000588 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000589 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000590 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000591 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000592 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
593 State.ForLoopVariablePos = State.Column -
594 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000595
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000596 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
597 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000598 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000599
Daniel Jasperf7935112012-12-03 18:12:45 +0000600 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000601 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000602
Daniel Jasperbcab4302013-01-09 10:40:23 +0000603 // FIXME: Do we need to do this for assignments nested in other
604 // expressions?
605 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000606 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000607 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000608 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000609 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000610 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000611 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000612 if (Current.getPreviousNoneComment() != NULL &&
613 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000614 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000615 State.Stack[ParenLevel].HasMultiParameterLine = true;
616
Daniel Jaspere9de2602012-12-06 09:56:08 +0000617 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000618 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
619 // Treat the condition inside an if as if it was a second function
620 // parameter, i.e. let nested calls have an indent of 4.
621 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000622 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000623 // Top-level spaces are exempt as that mostly leads to better results.
624 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000625 else if (Previous.ParameterCount > 1 &&
626 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
627 Previous.Type == TT_TemplateOpener))
628 // If this function has multiple parameters, indent nested calls from
629 // the start of the first parameter.
630 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000631 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000632
633 // If we break after an {, we should also break before the corresponding }.
634 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000635 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000636
Daniel Jaspere941b162013-01-23 10:08:28 +0000637 if (!Style.BinPackParameters && Newline) {
638 // If we are breaking after '(', '{', '<', this is not bin packing unless
639 // AllowAllParametersOnNextLine is false.
640 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
641 Previous.Type != TT_TemplateOpener) ||
642 !Style.AllowAllParametersOnNextLine)
643 State.Stack.back().BreakAfterComma = true;
644
645 // Any break on this level means that the parent level has been broken
646 // and we need to avoid bin packing there.
647 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
648 State.Stack[i].BreakAfterComma = true;
649 }
650 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000651
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000652 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000653 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000654
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000655 /// \brief Mark the next token as consumed in \p State and modify its stacks
656 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000657 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000658 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000659 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000660
Daniel Jasper337816e2013-01-11 10:22:12 +0000661 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
662 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000663
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000664 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000665 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000666 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
667 Current.is(tok::l_brace) ||
668 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000669 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000670 if (Current.is(tok::l_brace)) {
671 // FIXME: This does not work with nested static initializers.
672 // Implement a better handling for static initializers and similar
673 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000674 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000675 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000676 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000677 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000678 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000679 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000680 }
681
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000682 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000683 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000684 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
685 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
686 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000687 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000688 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000689
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000690 if (State.NextToken->Children.empty())
691 State.NextToken = NULL;
692 else
693 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000694
695 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000696 }
697
Nico Weber49cbc2c2013-01-07 15:15:29 +0000698 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000699 unsigned splitPenalty(const AnnotatedToken &Tok) {
700 const AnnotatedToken &Left = Tok;
701 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000702
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000703 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
704 return 50;
705 if (Left.is(tok::equal) && Right.is(tok::l_brace))
706 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000707 if (Left.is(tok::coloncolon))
708 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000709
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000710 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000711 if (RootToken.is(tok::kw_for) &&
712 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000713 return 20;
714
Daniel Jasper04468962013-01-18 10:56:38 +0000715 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000716 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000717
718 // In Objective-C method expressions, prefer breaking before "param:" over
719 // breaking after it.
720 if (isObjCSelectorName(Right))
721 return 0;
722 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
723 return 20;
724
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000725 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000726 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000727 // FIXME: The penalty for a trailing "<" or "[" being higher than the
728 // penalty for a trainling "(" is a temporary workaround until we can
729 // properly avoid breaking in array subscripts or template parameters.
730 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
731 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000732
Daniel Jasper399d24b2013-01-09 07:06:56 +0000733 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
734 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000735 prec::Level Level = getPrecedence(Left);
736
Daniel Jasperde5c2072012-12-24 00:13:23 +0000737 if (Level != prec::Unknown)
738 return Level;
739
Daniel Jasper04468962013-01-18 10:56:38 +0000740 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000741 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper04468962013-01-18 10:56:38 +0000742 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000743 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000744 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000745
Daniel Jasperf7935112012-12-03 18:12:45 +0000746 return 3;
747 }
748
Daniel Jasper2df93312013-01-09 10:16:05 +0000749 unsigned getColumnLimit() {
750 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
751 }
752
Daniel Jasperf7935112012-12-03 18:12:45 +0000753 /// \brief Calculate the number of lines needed to format the remaining part
754 /// of the unwrapped line.
755 ///
756 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000757 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000758 /// added after the previous token.
759 ///
760 /// \param StopAt is used for optimization. If we can determine that we'll
761 /// definitely need at least \p StopAt additional lines, we already know of a
762 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000763 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000764 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000765 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000766 return 0;
767
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000768 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000769 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000770 if (NewLine && !State.NextToken->CanBreakBefore &&
771 !(State.NextToken->is(tok::r_brace) &&
772 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000773 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000774 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000775 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000776 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000777 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000778 State.LineContainsContinuedForLoopSection)
779 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000780 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000781 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000782 State.Stack.back().BreakAfterComma)
783 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000784 // Trying to insert a parameter on a new line if there are already more than
785 // one parameter on the current line is bin packing.
786 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
787 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
788 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000789 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
790 (State.NextToken->Parent->ClosesTemplateDeclaration &&
791 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000792 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000793
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000794 unsigned CurrentPenalty = 0;
795 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000796 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000797 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000798 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000799 if (State.Stack.size() < State.StartOfLineLevel &&
800 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000801 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000802 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000803 }
804
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000805 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000806
Daniel Jasper2df93312013-01-09 10:16:05 +0000807 // Exceeding column limit is bad, assign penalty.
808 if (State.Column > getColumnLimit()) {
809 unsigned ExcessCharacters = State.Column - getColumnLimit();
810 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
811 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000812
Daniel Jasperf7935112012-12-03 18:12:45 +0000813 if (StopAt <= CurrentPenalty)
814 return UINT_MAX;
815 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000816 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000817 if (I != Memory.end()) {
818 // If this state has already been examined, we can safely return the
819 // previous result if we
820 // - have not hit the optimatization (and thus returned UINT_MAX) OR
821 // - are now computing for a smaller or equal StopAt.
822 unsigned SavedResult = I->second.first;
823 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000824 if (SavedResult != UINT_MAX)
825 return SavedResult + CurrentPenalty;
826 else if (StopAt <= SavedStopAt)
827 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000828 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000829
830 unsigned NoBreak = calcPenalty(State, false, StopAt);
831 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
832 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000833
834 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
835 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000836 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000837
838 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000839 }
840
Daniel Jasperf7935112012-12-03 18:12:45 +0000841 FormatStyle Style;
842 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000843 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000844 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000845 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000846 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000847
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000848 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000849 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000850 StateMap Memory;
851
Daniel Jasperf7935112012-12-03 18:12:45 +0000852 OptimizationParameters Parameters;
853};
854
855/// \brief Determines extra information about the tokens comprising an
856/// \c UnwrappedLine.
857class TokenAnnotator {
858public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000859 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
860 AnnotatedLine &Line)
861 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000862
863 /// \brief A parser that gathers additional information about tokens.
864 ///
865 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
866 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
867 /// into template parameter lists.
868 class AnnotatingParser {
869 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000871 : CurrentToken(&RootToken), KeywordVirtualFound(false),
872 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000873
Nico Weber250fe712013-01-18 02:43:57 +0000874 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
875 struct ObjCSelectorRAII {
876 AnnotatingParser &P;
877 bool ColonWasObjCMethodExpr;
878
879 ObjCSelectorRAII(AnnotatingParser &P)
880 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
881
882 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
883
884 void markStart(AnnotatedToken &Left) {
885 P.ColonIsObjCMethodExpr = true;
886 Left.Type = TT_ObjCMethodExpr;
887 }
888
889 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
890 };
891
892
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000893 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000894 if (CurrentToken == NULL)
895 return false;
896 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000897 while (CurrentToken != NULL) {
898 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000899 Left->MatchingParen = CurrentToken;
900 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000901 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000902 next();
903 return true;
904 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000905 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
906 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000907 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000908 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
909 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000910 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000911 if (CurrentToken->is(tok::comma))
912 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000913 if (!consumeToken())
914 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000915 }
916 return false;
917 }
918
Nico Weber80a82762013-01-17 17:17:19 +0000919 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000920 if (CurrentToken == NULL)
921 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000922 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000923 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000924 if (CurrentToken->is(tok::caret)) {
925 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000926 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000927 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
928 // @selector( starts a selector.
929 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
930 MaybeSel->Parent->is(tok::at)) {
931 StartsObjCMethodExpr = true;
932 }
933 }
934
935 ObjCSelectorRAII objCSelector(*this);
936 if (StartsObjCMethodExpr)
937 objCSelector.markStart(*Left);
938
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000939 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000940 // LookForDecls is set when "if (" has been seen. Check for
941 // 'identifier' '*' 'identifier' followed by not '=' -- this
942 // '*' has to be a binary operator but determineStarAmpUsage() will
943 // categorize it as an unary operator, so set the right type here.
944 if (LookForDecls && !CurrentToken->Children.empty()) {
945 AnnotatedToken &Prev = *CurrentToken->Parent;
946 AnnotatedToken &Next = CurrentToken->Children[0];
947 if (Prev.Parent->is(tok::identifier) &&
948 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
949 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
950 Prev.Type = TT_BinaryOperator;
951 LookForDecls = false;
952 }
953 }
954
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000955 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000956 Left->MatchingParen = CurrentToken;
957 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000958
959 if (StartsObjCMethodExpr)
960 objCSelector.markEnd(*CurrentToken);
961
Daniel Jasperf7935112012-12-03 18:12:45 +0000962 next();
963 return true;
964 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000965 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000966 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000967 if (CurrentToken->is(tok::comma))
968 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000969 if (!consumeToken())
970 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000971 }
972 return false;
973 }
974
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000975 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000976 if (!CurrentToken)
977 return false;
978
979 // A '[' could be an index subscript (after an indentifier or after
980 // ')' or ']'), or it could be the start of an Objective-C method
981 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000982 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000983 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000984 !Left->Parent || Left->Parent->is(tok::colon) ||
985 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
986 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
987 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000988 true, true) > prec::Unknown;
989
Nico Weber250fe712013-01-18 02:43:57 +0000990 ObjCSelectorRAII objCSelector(*this);
991 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000992 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000993
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000994 while (CurrentToken != NULL) {
995 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000996 if (!CurrentToken->Children.empty() &&
997 CurrentToken->Children[0].is(tok::l_paren)) {
998 // An ObjC method call can't be followed by an open parenthesis.
999 // FIXME: Do we incorrectly label ":" with this?
1000 StartsObjCMethodExpr = false;
1001 Left->Type = TT_Unknown;
1002 }
Nico Weber250fe712013-01-18 02:43:57 +00001003 if (StartsObjCMethodExpr)
1004 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001005 Left->MatchingParen = CurrentToken;
1006 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 next();
1008 return true;
1009 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001011 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001012 if (CurrentToken->is(tok::comma))
1013 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001014 if (!consumeToken())
1015 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 }
1017 return false;
1018 }
1019
Daniel Jasper83a54d22013-01-10 09:26:47 +00001020 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001021 // Lines are fine to end with '{'.
1022 if (CurrentToken == NULL)
1023 return true;
1024 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001025 while (CurrentToken != NULL) {
1026 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001027 Left->MatchingParen = CurrentToken;
1028 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001029 next();
1030 return true;
1031 }
1032 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1033 return false;
1034 if (!consumeToken())
1035 return false;
1036 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001037 return true;
1038 }
1039
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001040 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001041 while (CurrentToken != NULL) {
1042 if (CurrentToken->is(tok::colon)) {
1043 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 next();
1045 return true;
1046 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001047 if (!consumeToken())
1048 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 }
1050 return false;
1051 }
1052
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001053 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1055 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001056 next();
1057 if (!parseAngle())
1058 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001059 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001060 return true;
1061 }
1062 return false;
1063 }
1064
Daniel Jasperc0880a92013-01-04 18:52:56 +00001065 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001066 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001067 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001069 case tok::plus:
1070 case tok::minus:
1071 // At the start of the line, +/- specific ObjectiveC method
1072 // declarations.
1073 if (Tok->Parent == NULL)
1074 Tok->Type = TT_ObjCMethodSpecifier;
1075 break;
Nico Webera7252d82013-01-12 06:18:40 +00001076 case tok::colon:
1077 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001078 if (Tok->Parent->is(tok::r_paren))
1079 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001080 if (ColonIsObjCMethodExpr)
1081 Tok->Type = TT_ObjCMethodExpr;
1082 break;
Nico Weber80a82762013-01-17 17:17:19 +00001083 case tok::kw_if:
1084 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001085 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001086 next();
1087 if (!parseParens(/*LookForDecls=*/true))
1088 return false;
1089 }
1090 break;
Nico Webera5510af2013-01-18 05:50:57 +00001091 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001092 if (!parseParens())
1093 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001094 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001095 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001096 if (!parseSquare())
1097 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001098 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001099 case tok::l_brace:
1100 if (!parseBrace())
1101 return false;
1102 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001103 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001104 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001105 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001106 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001107 Tok->Type = TT_BinaryOperator;
1108 CurrentToken = Tok;
1109 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001110 }
1111 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001112 case tok::r_paren:
1113 case tok::r_square:
1114 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001115 case tok::r_brace:
1116 // Lines can start with '}'.
1117 if (Tok->Parent != NULL)
1118 return false;
1119 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001120 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001122 break;
1123 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001124 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001125 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001126 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001127 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1128 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001129 next();
1130 }
1131 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1133 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001134 next();
1135 }
1136 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001137 break;
1138 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001139 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001140 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001141 case tok::kw_template:
1142 parseTemplateDeclaration();
1143 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001144 default:
1145 break;
1146 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001147 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001148 }
1149
Daniel Jasper050948a52012-12-21 17:58:39 +00001150 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001151 next();
1152 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1153 next();
1154 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001155 if (CurrentToken->isNot(tok::comment) ||
1156 !CurrentToken->Children.empty())
1157 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001158 next();
1159 }
1160 } else {
1161 while (CurrentToken != NULL) {
1162 next();
1163 }
1164 }
1165 }
1166
1167 void parseWarningOrError() {
1168 next();
1169 // We still want to format the whitespace left of the first token of the
1170 // warning or error.
1171 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001172 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001173 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001174 next();
1175 }
1176 }
1177
1178 void parsePreprocessorDirective() {
1179 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001180 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001181 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001182 // Hashes in the middle of a line can lead to any strange token
1183 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001184 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001185 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001186 switch (
1187 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001188 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001189 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001190 parseIncludeDirective();
1191 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001192 case tok::pp_error:
1193 case tok::pp_warning:
1194 parseWarningOrError();
1195 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001196 default:
1197 break;
1198 }
1199 }
1200
Daniel Jasperda16db32013-01-07 10:48:50 +00001201 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001202 int PeriodsAndArrows = 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001203 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001204 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001205 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001206 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001207 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001208
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001209 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001210 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001211 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1212 ++PeriodsAndArrows;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001213 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001214 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001215 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001216 if (KeywordVirtualFound)
1217 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001218
1219 // Assume a builder-type call if there are 2 or more "." and "->".
1220 if (PeriodsAndArrows >= 2)
1221 return LT_BuilderTypeCall;
1222
Daniel Jasperda16db32013-01-07 10:48:50 +00001223 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001224 }
1225
1226 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001227 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1228 CurrentToken = &CurrentToken->Children[0];
1229 else
1230 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001231 }
1232
1233 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001234 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001235 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001236 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001237 };
1238
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001239 void calculateExtraInformation(AnnotatedToken &Current) {
1240 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1241
Manuel Klimek52b15152013-01-09 15:25:02 +00001242 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 Current.MustBreakBefore = true;
1244 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001245 if (Current.Type == TT_LineComment) {
1246 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001247 } else if ((Current.Parent->is(tok::comment) &&
1248 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001249 (Current.is(tok::string_literal) &&
1250 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001251 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001252 } else {
1253 Current.MustBreakBefore = false;
1254 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001255 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001256 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001257 if (Current.MustBreakBefore)
1258 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1259 else
1260 Current.TotalLength = Current.Parent->TotalLength +
1261 Current.FormatTok.TokenLength +
1262 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001263 if (!Current.Children.empty())
1264 calculateExtraInformation(Current.Children[0]);
1265 }
1266
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001268 AnnotatingParser Parser(Line.First);
1269 Line.Type = Parser.parseLine();
1270 if (Line.Type == LT_Invalid)
1271 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001272
Daniel Jasper5b49f472013-01-23 12:10:53 +00001273 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001274
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001275 if (Line.First.Type == TT_ObjCMethodSpecifier)
1276 Line.Type = LT_ObjCMethodDecl;
1277 else if (Line.First.Type == TT_ObjCDecl)
1278 Line.Type = LT_ObjCDecl;
1279 else if (Line.First.Type == TT_ObjCProperty)
1280 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001281
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001282 Line.First.SpaceRequiredBefore = true;
1283 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1284 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001285
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001286 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001287 if (!Line.First.Children.empty())
1288 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001289 }
1290
1291private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001292 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1293 if (getPrecedence(Current) == prec::Assignment) {
1294 IsExpression = true;
1295 AnnotatedToken *Previous = Current.Parent;
1296 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001297 if (Previous->Type == TT_BinaryOperator &&
1298 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001299 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001300 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001301 Previous = Previous->Parent;
1302 }
1303 }
1304 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001305 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1306 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001307 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001308
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001309 if (Current.Type == TT_Unknown) {
1310 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001311 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001312 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1313 Current.is(tok::caret)) {
1314 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001315 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1316 Current.Type = determineIncrementUsage(Current);
1317 } else if (Current.is(tok::exclaim)) {
1318 Current.Type = TT_UnaryOperator;
1319 } else if (isBinaryOperator(Current)) {
1320 Current.Type = TT_BinaryOperator;
1321 } else if (Current.is(tok::comment)) {
1322 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1323 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001324 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001325 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001326 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001327 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001328 } else if (Current.is(tok::r_paren) &&
1329 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001330 Current.Parent->Type == TT_TemplateCloser) &&
1331 (Current.Children.empty() ||
1332 (Current.Children[0].isNot(tok::equal) &&
1333 Current.Children[0].isNot(tok::semi) &&
1334 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001335 // FIXME: We need to get smarter and understand more cases of casts.
1336 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001337 } else if (Current.is(tok::at) && Current.Children.size()) {
1338 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1339 case tok::objc_interface:
1340 case tok::objc_implementation:
1341 case tok::objc_protocol:
1342 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001343 break;
1344 case tok::objc_property:
1345 Current.Type = TT_ObjCProperty;
1346 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001347 default:
1348 break;
1349 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001350 }
1351 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001352
1353 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001354 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001355 }
1356
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001357 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001358 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001359 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001360 }
1361
Daniel Jasper71945272013-01-15 14:27:39 +00001362 /// \brief Returns the previous token ignoring comments.
1363 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1364 const AnnotatedToken *PrevToken = Tok.Parent;
1365 while (PrevToken != NULL && PrevToken->is(tok::comment))
1366 PrevToken = PrevToken->Parent;
1367 return PrevToken;
1368 }
1369
1370 /// \brief Returns the next token ignoring comments.
1371 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1372 if (Tok.Children.empty())
1373 return NULL;
1374 const AnnotatedToken *NextToken = &Tok.Children[0];
1375 while (NextToken->is(tok::comment)) {
1376 if (NextToken->Children.empty())
1377 return NULL;
1378 NextToken = &NextToken->Children[0];
1379 }
1380 return NextToken;
1381 }
1382
1383 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001384 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1385 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001386 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1387 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001388 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001389
1390 const AnnotatedToken *NextToken = getNextToken(Tok);
1391 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001392 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001393
Daniel Jasper0b820602013-01-22 11:46:26 +00001394 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1395 return TT_PointerOrReference;
1396
Daniel Jasper71945272013-01-15 14:27:39 +00001397 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1398 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1399 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1400 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001401 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001402 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001403
Daniel Jasper71945272013-01-15 14:27:39 +00001404 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1405 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1406 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1407 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1408 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1409 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1410 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001411 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001412
Daniel Jasper71945272013-01-15 14:27:39 +00001413 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1414 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001415 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001416
Daniel Jasper426702d2012-12-05 07:51:39 +00001417 // It is very unlikely that we are going to find a pointer or reference type
1418 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001419 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001420 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001421
Daniel Jasperda16db32013-01-07 10:48:50 +00001422 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001423 }
1424
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001425 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001426 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1427 if (PrevToken == NULL)
1428 return TT_UnaryOperator;
1429
Daniel Jasper8dd40472012-12-21 09:41:31 +00001430 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001431 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1432 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1433 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1434 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1435 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001436 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001437
1438 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001439 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001440 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001441
1442 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001443 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001444 }
1445
1446 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001447 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001448 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1449 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001450 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001451 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1452 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001453 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001454
Daniel Jasperda16db32013-01-07 10:48:50 +00001455 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001456 }
1457
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001458 bool spaceRequiredBetween(const AnnotatedToken &Left,
1459 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001460 if (Right.is(tok::hashhash))
1461 return Left.is(tok::hash);
1462 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1463 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001464 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1465 return false;
Nico Webera6087752013-01-10 20:12:55 +00001466 if (Right.is(tok::less) &&
1467 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001468 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001469 return true;
1470 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1471 return false;
1472 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1473 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001474 if (Left.is(tok::at) &&
1475 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1476 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001477 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1478 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001479 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001480 if (Left.is(tok::coloncolon))
1481 return false;
1482 if (Right.is(tok::coloncolon))
1483 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001484 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1485 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001486 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001487 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001488 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1489 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001490 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001491 return Right.FormatTok.Tok.isLiteral() ||
1492 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001493 if (Right.is(tok::star) && Left.is(tok::l_paren))
1494 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001495 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1496 return false;
1497 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001498 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001499 if (Left.is(tok::period) || Right.is(tok::period))
1500 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001501 if (Left.is(tok::colon))
1502 return Left.Type != TT_ObjCMethodExpr;
1503 if (Right.is(tok::colon))
1504 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001505 if (Left.is(tok::l_paren))
1506 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001507 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001508 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001509 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001510 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001511 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1512 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001513 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001514 if (Left.is(tok::at) &&
1515 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001516 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001517 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1518 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001519 return true;
1520 }
1521
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001522 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001523 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001524 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1525 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001526 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001527 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001528 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001529 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001530 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001531 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001532 // Don't space between ')' and <id>
1533 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001534 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001535 // Don't space between ':' and '('
1536 return false;
1537 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001538 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001539 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1540 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001541
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001542 if (Tok.Parent->is(tok::comma))
1543 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001544 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001545 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001546 if (Tok.Type == TT_OverloadedOperator)
1547 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001548 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001549 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001550 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001551 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001552 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001553 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001554 if (Tok.Parent->Type == TT_UnaryOperator ||
1555 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001556 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001557 if (Tok.Type == TT_UnaryOperator)
1558 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001559 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1560 (Tok.Parent->isNot(tok::colon) ||
1561 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001562 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1563 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001564 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1565 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001566 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001567 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001568 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001569 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001570 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001571 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001572 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001573 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001575 }
1576
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001577 bool canBreakBefore(const AnnotatedToken &Right) {
1578 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001579 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001580 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1581 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001582 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001583 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1584 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001585 // Don't break this identifier as ':' or identifier
1586 // before it will break.
1587 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001588 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1589 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001590 // Don't break at ':' if identifier before it can beak.
1591 return false;
1592 }
Nico Webera7252d82013-01-12 06:18:40 +00001593 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1594 return false;
1595 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1596 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001597 if (isObjCSelectorName(Right))
1598 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001599 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001600 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001601 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001602 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001603 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001604 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001605 return false;
1606
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001607 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001608 // We rely on MustBreakBefore being set correctly here as we should not
1609 // change the "binding" behavior of a comment.
1610 return false;
1611
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001612 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1613 // unless it is follow by ';', '{' or '='.
1614 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1615 Left.Parent->is(tok::r_paren))
1616 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1617 Right.isNot(tok::equal);
1618
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001619 // We only break before r_brace if there was a corresponding break before
1620 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1621 if (Right.is(tok::r_brace))
1622 return false;
1623
Daniel Jasper71945272013-01-15 14:27:39 +00001624 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001625 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001626 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1627 Left.is(tok::comma) || Right.is(tok::lessless) ||
1628 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001629 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1630 Left.is(tok::semi) || Left.is(tok::l_brace) ||
1631 Left.is(tok::question) || Left.Type == TT_ConditionalExpr ||
1632 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1633 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001634 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1635 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001636 }
1637
Daniel Jasperf7935112012-12-03 18:12:45 +00001638 FormatStyle Style;
1639 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001640 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001641 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001642};
1643
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001644class LexerBasedFormatTokenSource : public FormatTokenSource {
1645public:
1646 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001647 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001648 IdentTable(Lex.getLangOpts()) {
1649 Lex.SetKeepWhitespaceMode(true);
1650 }
1651
1652 virtual FormatToken getNextToken() {
1653 if (GreaterStashed) {
1654 FormatTok.NewlinesBefore = 0;
1655 FormatTok.WhiteSpaceStart =
1656 FormatTok.Tok.getLocation().getLocWithOffset(1);
1657 FormatTok.WhiteSpaceLength = 0;
1658 GreaterStashed = false;
1659 return FormatTok;
1660 }
1661
1662 FormatTok = FormatToken();
1663 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001664 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001665 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001666 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1667 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001668
1669 // Consume and record whitespace until we find a significant token.
1670 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001671 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001672 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1673 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001674 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1675
1676 if (FormatTok.Tok.is(tok::eof))
1677 return FormatTok;
1678 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001679 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001680 }
Manuel Klimekef920692013-01-07 07:56:50 +00001681
1682 // Now FormatTok is the next non-whitespace token.
1683 FormatTok.TokenLength = Text.size();
1684
Manuel Klimek1abf7892013-01-04 23:34:14 +00001685 // In case the token starts with escaped newlines, we want to
1686 // take them into account as whitespace - this pattern is quite frequent
1687 // in macro definitions.
1688 // FIXME: What do we want to do with other escaped spaces, and escaped
1689 // spaces or newlines in the middle of tokens?
1690 // FIXME: Add a more explicit test.
1691 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001692 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001693 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001694 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001695 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001696 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001697 }
1698
1699 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001700 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001701 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001702 FormatTok.Tok.setKind(Info.getTokenID());
1703 }
1704
1705 if (FormatTok.Tok.is(tok::greatergreater)) {
1706 FormatTok.Tok.setKind(tok::greater);
1707 GreaterStashed = true;
1708 }
1709
1710 return FormatTok;
1711 }
1712
1713private:
1714 FormatToken FormatTok;
1715 bool GreaterStashed;
1716 Lexer &Lex;
1717 SourceManager &SourceMgr;
1718 IdentifierTable IdentTable;
1719
1720 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001721 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001722 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1723 Tok.getLength());
1724 }
1725};
1726
Daniel Jasperf7935112012-12-03 18:12:45 +00001727class Formatter : public UnwrappedLineConsumer {
1728public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001729 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1730 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001731 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001732 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001733 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001734
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001735 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001736
Daniel Jasperf7935112012-12-03 18:12:45 +00001737 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001738 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001739 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001740 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001741 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001742 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1743 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1744 Annotator.annotate();
1745 }
1746 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1747 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001748 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001749 const AnnotatedLine &TheLine = *I;
1750 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1751 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1752 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001753 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001754 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001755 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001756 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001757 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001758 PreviousEndOfLineColumn = Formatter.format();
1759 } else {
1760 // If we did not reformat this unwrapped line, the column at the end of
1761 // the last token is unchanged - thus, we can calculate the end of the
1762 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001763 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001764 SourceMgr.getSpellingColumnNumber(
1765 TheLine.Last->FormatTok.Tok.getLocation()) +
1766 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1767 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001768 1;
1769 }
1770 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001771 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001772 }
1773
1774private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001775 /// \brief Tries to merge lines into one.
1776 ///
1777 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1778 /// if possible; note that \c I will be incremented when lines are merged.
1779 ///
1780 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001781 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001782 std::vector<AnnotatedLine>::iterator &I,
1783 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001784 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1785
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001786 // We can never merge stuff if there are trailing line comments.
1787 if (I->Last->Type == TT_LineComment)
1788 return;
1789
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001790 // Check whether the UnwrappedLine can be put onto a single line. If
1791 // so, this is bound to be the optimal solution (by definition) and we
1792 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001793 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001794 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001795 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001796
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001797 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001798 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001799
Daniel Jasper25837aa2013-01-14 14:14:23 +00001800 if (I->Last->is(tok::l_brace)) {
1801 tryMergeSimpleBlock(I, E, Limit);
1802 } else if (I->First.is(tok::kw_if)) {
1803 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001804 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1805 I->First.FormatTok.IsFirst)) {
1806 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001807 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001808 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001809 }
1810
Daniel Jasper39825ea2013-01-14 15:40:57 +00001811 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1812 std::vector<AnnotatedLine>::iterator E,
1813 unsigned Limit) {
1814 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001815 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1816 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001817 if (I + 2 != E && (I + 2)->InPPDirective &&
1818 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1819 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001820 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001821 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001822 join(Line, *(++I));
1823 }
1824
Daniel Jasper25837aa2013-01-14 14:14:23 +00001825 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1826 std::vector<AnnotatedLine>::iterator E,
1827 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001828 if (!Style.AllowShortIfStatementsOnASingleLine)
1829 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001830 if ((I + 1)->InPPDirective != I->InPPDirective ||
1831 ((I + 1)->InPPDirective &&
1832 (I + 1)->First.FormatTok.HasUnescapedNewline))
1833 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001834 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001835 if (Line.Last->isNot(tok::r_paren))
1836 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001837 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001838 return;
1839 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1840 return;
1841 // Only inline simple if's (no nested if or else).
1842 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1843 return;
1844 join(Line, *(++I));
1845 }
1846
1847 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1848 std::vector<AnnotatedLine>::iterator E,
1849 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001850 // First, check that the current line allows merging. This is the case if
1851 // we're not in a control flow statement and the last token is an opening
1852 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001853 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001854 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001855 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1856 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1857 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1858 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001859 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001860 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1861 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001862 if (!AllowedTokens)
1863 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001864
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001865 AnnotatedToken *Tok = &(I + 1)->First;
1866 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1867 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1868 Tok->SpaceRequiredBefore = false;
1869 join(Line, *(I + 1));
1870 I += 1;
1871 } else {
1872 // Check that we still have three lines and they fit into the limit.
1873 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1874 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001875 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001876
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001877 // Second, check that the next line does not contain any braces - if it
1878 // does, readability declines when putting it into a single line.
1879 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1880 return;
1881 do {
1882 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1883 return;
1884 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1885 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001886
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001887 // Last, check that the third line contains a single closing brace.
1888 Tok = &(I + 2)->First;
1889 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1890 Tok->MustBreakBefore)
1891 return;
1892
1893 join(Line, *(I + 1));
1894 join(Line, *(I + 2));
1895 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001896 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001897 }
1898
1899 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1900 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001901 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1902 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001903 }
1904
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001905 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1906 A.Last->Children.push_back(B.First);
1907 while (!A.Last->Children.empty()) {
1908 A.Last->Children[0].Parent = A.Last;
1909 A.Last = &A.Last->Children[0];
1910 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001911 }
1912
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001913 bool touchesRanges(const AnnotatedLine &TheLine) {
1914 const FormatToken *First = &TheLine.First.FormatTok;
1915 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001916 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001917 First->Tok.getLocation(),
1918 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001919 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001920 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1921 Ranges[i].getBegin()) &&
1922 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1923 LineRange.getBegin()))
1924 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001925 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001926 return false;
1927 }
1928
1929 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001930 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001931 }
1932
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001933 /// \brief Add a new line and the required indent before the first Token
1934 /// of the \c UnwrappedLine if there was no structural parsing error.
1935 /// Returns the indent level of the \c UnwrappedLine.
1936 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1937 bool InPPDirective,
1938 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001939 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001940 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1941 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1942
1943 unsigned Newlines = std::min(Tok.NewlinesBefore,
1944 Style.MaxEmptyLinesToKeep + 1);
1945 if (Newlines == 0 && !Tok.IsFirst)
1946 Newlines = 1;
1947 unsigned Indent = Level * 2;
1948
1949 bool IsAccessModifier = false;
1950 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1951 RootToken.is(tok::kw_private))
1952 IsAccessModifier = true;
1953 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1954 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1955 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1956 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1957 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1958 IsAccessModifier = true;
1959
1960 if (IsAccessModifier &&
1961 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1962 Indent += Style.AccessModifierOffset;
1963 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001964 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001965 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001966 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1967 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001968 }
1969 return Indent;
1970 }
1971
Alexander Kornienko116ba682013-01-14 11:34:14 +00001972 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001973 FormatStyle Style;
1974 Lexer &Lex;
1975 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001976 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001977 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001978 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001979 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001980};
1981
1982tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1983 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001984 std::vector<CharSourceRange> Ranges,
1985 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001986 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001987 OwningPtr<DiagnosticConsumer> DiagPrinter;
1988 if (DiagClient == 0) {
1989 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1990 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1991 DiagClient = DiagPrinter.get();
1992 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001993 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001994 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001995 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001996 Diagnostics.setSourceManager(&SourceMgr);
1997 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001998 return formatter.format();
1999}
2000
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002001LangOptions getFormattingLangOpts() {
2002 LangOptions LangOpts;
2003 LangOpts.CPlusPlus = 1;
2004 LangOpts.CPlusPlus11 = 1;
2005 LangOpts.Bool = 1;
2006 LangOpts.ObjC1 = 1;
2007 LangOpts.ObjC2 = 1;
2008 return LangOpts;
2009}
2010
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002011} // namespace format
2012} // namespace clang