blob: 1405fc23e1f2ef5ff4f862ebdcfd52548f4a7219 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000063 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000064 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000069};
70
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000073 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper9278eb92013-01-16 14:59:02 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000077
Daniel Jasper25837aa2013-01-14 14:14:23 +000078 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
79 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
80
Daniel Jasper7c85fde2013-01-08 14:56:18 +000081 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
82 return FormatTok.Tok.isObjCAtKeyword(Kind);
83 }
84
85 FormatToken FormatTok;
86
Daniel Jasperf7935112012-12-03 18:12:45 +000087 TokenType Type;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 bool SpaceRequiredBefore;
90 bool CanBreakBefore;
91 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000092
93 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000094
Daniel Jasper9278eb92013-01-16 14:59:02 +000095 AnnotatedToken *MatchingParen;
96
Daniel Jaspera67a8f02013-01-16 10:41:46 +000097 /// \brief The total length of the line up to and including this token.
98 unsigned TotalLength;
99
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000100 std::vector<AnnotatedToken> Children;
101 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000102
103 const AnnotatedToken *getPreviousNoneComment() const {
104 AnnotatedToken *Tok = Parent;
105 while (Tok != NULL && Tok->is(tok::comment))
106 Tok = Tok->Parent;
107 return Tok;
108 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000109};
110
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000111class AnnotatedLine {
112public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000113 AnnotatedLine(const UnwrappedLine &Line)
114 : First(Line.Tokens.front()), Level(Line.Level),
115 InPPDirective(Line.InPPDirective) {
116 assert(!Line.Tokens.empty());
117 AnnotatedToken *Current = &First;
118 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
119 E = Line.Tokens.end();
120 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000121 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000122 Current->Children[0].Parent = Current;
123 Current = &Current->Children[0];
124 }
125 Last = Current;
126 }
127 AnnotatedLine(const AnnotatedLine &Other)
128 : First(Other.First), Type(Other.Type), Level(Other.Level),
129 InPPDirective(Other.InPPDirective) {
130 Last = &First;
131 while (!Last->Children.empty()) {
132 Last->Children[0].Parent = Last;
133 Last = &Last->Children[0];
134 }
135 }
136
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000137 AnnotatedToken First;
138 AnnotatedToken *Last;
139
140 LineType Type;
141 unsigned Level;
142 bool InPPDirective;
143};
144
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000145static prec::Level getPrecedence(const AnnotatedToken &Tok) {
146 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000147}
148
Daniel Jasperf7935112012-12-03 18:12:45 +0000149FormatStyle getLLVMStyle() {
150 FormatStyle LLVMStyle;
151 LLVMStyle.ColumnLimit = 80;
152 LLVMStyle.MaxEmptyLinesToKeep = 1;
153 LLVMStyle.PointerAndReferenceBindToType = false;
154 LLVMStyle.AccessModifierOffset = -2;
155 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000156 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000157 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000158 LLVMStyle.BinPackParameters = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000159 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000160 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000161 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000162 return LLVMStyle;
163}
164
165FormatStyle getGoogleStyle() {
166 FormatStyle GoogleStyle;
167 GoogleStyle.ColumnLimit = 80;
168 GoogleStyle.MaxEmptyLinesToKeep = 1;
169 GoogleStyle.PointerAndReferenceBindToType = true;
170 GoogleStyle.AccessModifierOffset = -1;
171 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000172 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000173 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000174 GoogleStyle.BinPackParameters = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000175 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000176 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000177 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000178 return GoogleStyle;
179}
180
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000181FormatStyle getChromiumStyle() {
182 FormatStyle ChromiumStyle = getGoogleStyle();
183 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
184 return ChromiumStyle;
185}
186
Daniel Jasperf7935112012-12-03 18:12:45 +0000187struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000188 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000189 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000190 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000191};
192
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000193/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000194///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000195/// This includes special handling for certain constructs, e.g. the alignment of
196/// trailing line comments.
197class WhitespaceManager {
198public:
199 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
200
201 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
202 /// each \c AnnotatedToken.
203 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
204 unsigned Spaces, unsigned WhitespaceStartColumn,
205 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000206 // 2+ newlines mean an empty line separating logic scopes.
207 if (NewLines >= 2)
208 alignComments();
209
210 // Align line comments if they are trailing or if they continue other
211 // trailing comments.
212 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000213 (Tok.Parent != NULL || !Comments.empty())) {
214 if (Style.ColumnLimit >=
215 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
216 Comments.push_back(StoredComment());
217 Comments.back().Tok = Tok.FormatTok;
218 Comments.back().Spaces = Spaces;
219 Comments.back().NewLines = NewLines;
220 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
221 Comments.back().MaxColumn = Style.ColumnLimit -
222 Spaces - Tok.FormatTok.TokenLength;
223 return;
224 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000225 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000226
227 // If this line does not have a trailing comment, align the stored comments.
228 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
229 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000230 storeReplacement(Tok.FormatTok,
231 std::string(NewLines, '\n') + std::string(Spaces, ' '));
232 }
233
234 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
235 /// backslashes to escape newlines inside a preprocessor directive.
236 ///
237 /// This function and \c replaceWhitespace have the same behavior if
238 /// \c Newlines == 0.
239 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
240 unsigned Spaces, unsigned WhitespaceStartColumn,
241 const FormatStyle &Style) {
242 std::string NewLineText;
243 if (NewLines > 0) {
244 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
245 WhitespaceStartColumn);
246 for (unsigned i = 0; i < NewLines; ++i) {
247 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
248 NewLineText += "\\\n";
249 Offset = 0;
250 }
251 }
252 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
253 }
254
255 /// \brief Returns all the \c Replacements created during formatting.
256 const tooling::Replacements &generateReplacements() {
257 alignComments();
258 return Replaces;
259 }
260
261private:
262 /// \brief Structure to store a comment for later layout and alignment.
263 struct StoredComment {
264 FormatToken Tok;
265 unsigned MinColumn;
266 unsigned MaxColumn;
267 unsigned NewLines;
268 unsigned Spaces;
269 };
270 SmallVector<StoredComment, 16> Comments;
271 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
272
273 /// \brief Try to align all stashed comments.
274 void alignComments() {
275 unsigned MinColumn = 0;
276 unsigned MaxColumn = UINT_MAX;
277 comment_iterator Start = Comments.begin();
278 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
279 ++I) {
280 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
281 alignComments(Start, I, MinColumn);
282 MinColumn = I->MinColumn;
283 MaxColumn = I->MaxColumn;
284 Start = I;
285 } else {
286 MinColumn = std::max(MinColumn, I->MinColumn);
287 MaxColumn = std::min(MaxColumn, I->MaxColumn);
288 }
289 }
290 alignComments(Start, Comments.end(), MinColumn);
291 Comments.clear();
292 }
293
294 /// \brief Put all the comments between \p I and \p E into \p Column.
295 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
296 while (I != E) {
297 unsigned Spaces = I->Spaces + Column - I->MinColumn;
298 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
299 std::string(Spaces, ' '));
300 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000301 }
302 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000303
304 /// \brief Stores \p Text as the replacement for the whitespace in front of
305 /// \p Tok.
306 void storeReplacement(const FormatToken &Tok, const std::string Text) {
307 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
308 Tok.WhiteSpaceLength, Text));
309 }
310
311 SourceManager &SourceMgr;
312 tooling::Replacements Replaces;
313};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000314
Nico Weberc9d73612013-01-12 22:48:47 +0000315/// \brief Returns if a token is an Objective-C selector name.
316///
Nico Weber92c05392013-01-12 22:51:13 +0000317/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000318static bool isObjCSelectorName(const AnnotatedToken &Tok) {
319 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
320 Tok.Children[0].is(tok::colon) &&
321 Tok.Children[0].Type == TT_ObjCMethodExpr;
322}
323
Daniel Jasperf7935112012-12-03 18:12:45 +0000324class UnwrappedLineFormatter {
325public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000326 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000327 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000328 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000329 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000330 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000331 FirstIndent(FirstIndent), RootToken(RootToken),
332 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000333 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000334 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000335 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000336 }
337
Manuel Klimek1abf7892013-01-04 23:34:14 +0000338 /// \brief Formats an \c UnwrappedLine.
339 ///
340 /// \returns The column after the last token in the last line of the
341 /// \c UnwrappedLine.
342 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000343 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000344 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000345 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000346 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000347 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000348 State.ForLoopVariablePos = 0;
349 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000350 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000351
Manuel Klimek24998102013-01-16 14:55:28 +0000352 DEBUG({
353 DebugTokenState(*State.NextToken);
354 });
355
Daniel Jaspere9de2602012-12-06 09:56:08 +0000356 // The first token has already been indented and thus consumed.
357 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000358
359 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000360 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000361 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
362 // Calculating the column is important for aligning trailing comments.
363 // FIXME: This does not seem to happen in conjunction with escaped
364 // newlines. If it does, fix!
365 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
366 State.NextToken->FormatTok.TokenLength;
367 State.NextToken = State.NextToken->Children.empty() ? NULL :
368 &State.NextToken->Children[0];
369 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000370 addTokenToState(false, false, State);
371 } else {
372 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
373 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000374 DEBUG({
375 if (Break < NoBreak)
376 llvm::errs() << "\n";
377 else
378 llvm::errs() << " ";
379 llvm::errs() << "<";
380 DebugPenalty(Break, Break < NoBreak);
381 llvm::errs() << "/";
382 DebugPenalty(NoBreak, !(Break < NoBreak));
383 llvm::errs() << "> ";
384 DebugTokenState(*State.NextToken);
385 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000386 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000387 if (State.NextToken != NULL &&
388 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
389 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000390 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000391 State.Stack.back().BreakAfterComma = true;
392 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000393 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000394 }
Manuel Klimek24998102013-01-16 14:55:28 +0000395 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000396 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000397 }
398
399private:
Manuel Klimek24998102013-01-16 14:55:28 +0000400 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
401 const Token &Tok = AnnotatedTok.FormatTok.Tok;
402 llvm::errs()
403 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
404 Tok.getLength());
405 llvm::errs();
406 }
407
408 void DebugPenalty(unsigned Penalty, bool Winner) {
409 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
410 if (Penalty == UINT_MAX)
411 llvm::errs() << "MAX";
412 else
413 llvm::errs() << Penalty;
414 llvm::errs().resetColor();
415 }
416
Daniel Jasper337816e2013-01-11 10:22:12 +0000417 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000418 ParenState(unsigned Indent, unsigned LastSpace)
419 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000420 BreakBeforeClosingBrace(false), BreakAfterComma(false),
421 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000422
Daniel Jasperf7935112012-12-03 18:12:45 +0000423 /// \brief The position to which a specific parenthesis level needs to be
424 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000425 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000426
Daniel Jaspere9de2602012-12-06 09:56:08 +0000427 /// \brief The position of the last space on each level.
428 ///
429 /// Used e.g. to break like:
430 /// functionCall(Parameter, otherCall(
431 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000432 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000433
Daniel Jaspere9de2602012-12-06 09:56:08 +0000434 /// \brief The position the first "<<" operator encountered on each level.
435 ///
436 /// Used to align "<<" operators. 0 if no such operator has been encountered
437 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000438 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000439
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000440 /// \brief Whether a newline needs to be inserted before the block's closing
441 /// brace.
442 ///
443 /// We only want to insert a newline before the closing brace if there also
444 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 bool BreakBeforeClosingBrace;
446
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000447 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000448 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000449
Daniel Jasper337816e2013-01-11 10:22:12 +0000450 bool operator<(const ParenState &Other) const {
451 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000452 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000453 if (LastSpace != Other.LastSpace)
454 return LastSpace < Other.LastSpace;
455 if (FirstLessLess != Other.FirstLessLess)
456 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000457 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
458 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000459 if (BreakAfterComma != Other.BreakAfterComma)
460 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000461 if (HasMultiParameterLine != Other.HasMultiParameterLine)
462 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000463 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000464 }
465 };
466
467 /// \brief The current state when indenting a unwrapped line.
468 ///
469 /// As the indenting tries different combinations this is copied by value.
470 struct LineState {
471 /// \brief The number of used columns in the current line.
472 unsigned Column;
473
474 /// \brief The token that needs to be next formatted.
475 const AnnotatedToken *NextToken;
476
477 /// \brief The parenthesis level of the first token on the current line.
478 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000479
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000480 /// \brief The column of the first variable in a for-loop declaration.
481 ///
482 /// Used to align the second variable if necessary.
483 unsigned ForLoopVariablePos;
484
485 /// \brief \c true if this line contains a continued for-loop section.
486 bool LineContainsContinuedForLoopSection;
487
Daniel Jasper337816e2013-01-11 10:22:12 +0000488 /// \brief A stack keeping track of properties applying to parenthesis
489 /// levels.
490 std::vector<ParenState> Stack;
491
492 /// \brief Comparison operator to be able to used \c LineState in \c map.
493 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000494 if (Other.NextToken != NextToken)
495 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000496 if (Other.Column != Column)
497 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000498 if (Other.StartOfLineLevel != StartOfLineLevel)
499 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000500 if (Other.ForLoopVariablePos != ForLoopVariablePos)
501 return Other.ForLoopVariablePos < ForLoopVariablePos;
502 if (Other.LineContainsContinuedForLoopSection !=
503 LineContainsContinuedForLoopSection)
504 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000505 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000506 }
507 };
508
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000509 /// \brief Appends the next token to \p State and updates information
510 /// necessary for indentation.
511 ///
512 /// Puts the token on the current line if \p Newline is \c true and adds a
513 /// line break and necessary indentation otherwise.
514 ///
515 /// If \p DryRun is \c false, also creates and stores the required
516 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000517 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000518 const AnnotatedToken &Current = *State.NextToken;
519 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000520 assert(State.Stack.size());
521 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000522
523 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000524 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000525 if (Current.is(tok::r_brace)) {
526 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000527 } else if (Current.is(tok::string_literal) &&
528 Previous.is(tok::string_literal)) {
529 State.Column = State.Column - Previous.FormatTok.TokenLength;
530 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000531 State.Stack[ParenLevel].FirstLessLess != 0) {
532 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000533 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000534 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
535 Current.is(tok::period) || Previous.is(tok::question) ||
536 Previous.Type == TT_ConditionalExpr)) {
537 // Indent and extra 4 spaces after if we know the current expression is
538 // continued. Don't do that on the top level, as we already indent 4
539 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000540 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000541 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000542 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000543 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000544 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000545 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000546 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000547 }
548
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000549 // A line starting with a closing brace is assumed to be correct for the
550 // same level as before the opening brace.
551 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000552
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000553 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000554 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000555
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000556 if (!DryRun) {
557 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000558 Whitespaces.replaceWhitespace(Current, 1, State.Column,
559 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000560 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000561 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
562 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000563 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000564
Daniel Jasper337816e2013-01-11 10:22:12 +0000565 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000566 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000567 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000568 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000569 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
570 State.ForLoopVariablePos = State.Column -
571 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000572
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000573 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
574 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000575 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000576
Daniel Jasperf7935112012-12-03 18:12:45 +0000577 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000578 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000579
Daniel Jasperbcab4302013-01-09 10:40:23 +0000580 // FIXME: Do we need to do this for assignments nested in other
581 // expressions?
582 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000583 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000584 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000585 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000586 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000587 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000588 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000589 if (Current.getPreviousNoneComment() != NULL &&
590 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000591 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000592 State.Stack[ParenLevel].HasMultiParameterLine = true;
593
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000594
Daniel Jasper206df732013-01-07 13:08:40 +0000595 // Top-level spaces that are not part of assignments are exempt as that
596 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000597 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000598 if (Spaces > 0 &&
599 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000600 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000601 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000602
603 // If we break after an {, we should also break before the corresponding }.
604 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000605 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000606
607 // If we are breaking after '(', '{', '<' or ',', we need to break after
608 // future commas as well to avoid bin packing.
609 if (!Style.BinPackParameters && Newline &&
610 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
611 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
612 State.Stack.back().BreakAfterComma = true;
613
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000614 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000615 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000616
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000617 /// \brief Mark the next token as consumed in \p State and modify its stacks
618 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000619 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000620 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000621 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000622
Daniel Jasper337816e2013-01-11 10:22:12 +0000623 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
624 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000625
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000626 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000627 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000628 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
629 Current.is(tok::l_brace) ||
630 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000631 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000632 if (Current.is(tok::l_brace)) {
633 // FIXME: This does not work with nested static initializers.
634 // Implement a better handling for static initializers and similar
635 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000636 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000637 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000638 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000639 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000640 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000641 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000642
643 // If the entire set of parameters will not fit on the current line, we
644 // will need to break after commas on this level to avoid bin-packing.
645 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
646 !Current.Children.empty()) {
647 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
648 Current.MatchingParen->TotalLength -
649 Current.Children[0].TotalLength) {
650 State.Stack.back().BreakAfterComma = true;
651 }
652 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000653 }
654
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000655 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000656 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000657 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
658 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
659 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000660 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000661 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000662
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000663 if (State.NextToken->Children.empty())
664 State.NextToken = NULL;
665 else
666 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000667
668 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000669 }
670
Nico Weber49cbc2c2013-01-07 15:15:29 +0000671 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000672 unsigned splitPenalty(const AnnotatedToken &Tok) {
673 const AnnotatedToken &Left = Tok;
674 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000675
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000676 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
677 return 50;
678 if (Left.is(tok::equal) && Right.is(tok::l_brace))
679 return 150;
680
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000681 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000682 if (RootToken.is(tok::kw_for) &&
683 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000684 return 20;
685
Daniel Jasper04468962013-01-18 10:56:38 +0000686 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000687 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000688
689 // In Objective-C method expressions, prefer breaking before "param:" over
690 // breaking after it.
691 if (isObjCSelectorName(Right))
692 return 0;
693 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
694 return 20;
695
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000696 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000697 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000698
Daniel Jasper399d24b2013-01-09 07:06:56 +0000699 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
700 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000701 prec::Level Level = getPrecedence(Left);
702
703 // Breaking after an assignment leads to a bad result as the two sides of
704 // the assignment are visually very close together.
705 if (Level == prec::Assignment)
706 return 50;
707
Daniel Jasperde5c2072012-12-24 00:13:23 +0000708 if (Level != prec::Unknown)
709 return Level;
710
Daniel Jasper04468962013-01-18 10:56:38 +0000711 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000712 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper04468962013-01-18 10:56:38 +0000713 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000714 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000715 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000716
Daniel Jasperf7935112012-12-03 18:12:45 +0000717 return 3;
718 }
719
Daniel Jasper2df93312013-01-09 10:16:05 +0000720 unsigned getColumnLimit() {
721 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
722 }
723
Daniel Jasperf7935112012-12-03 18:12:45 +0000724 /// \brief Calculate the number of lines needed to format the remaining part
725 /// of the unwrapped line.
726 ///
727 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000728 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000729 /// added after the previous token.
730 ///
731 /// \param StopAt is used for optimization. If we can determine that we'll
732 /// definitely need at least \p StopAt additional lines, we already know of a
733 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000734 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000736 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000737 return 0;
738
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000739 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000740 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000741 if (NewLine && !State.NextToken->CanBreakBefore &&
742 !(State.NextToken->is(tok::r_brace) &&
743 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000744 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000745 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000746 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000747 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000748 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000749 State.LineContainsContinuedForLoopSection)
750 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000751 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000752 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000753 State.Stack.back().BreakAfterComma)
754 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000755 // Trying to insert a parameter on a new line if there are already more than
756 // one parameter on the current line is bin packing.
757 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
758 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
759 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000760 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
761 (State.NextToken->Parent->ClosesTemplateDeclaration &&
762 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000763 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000764
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000765 unsigned CurrentPenalty = 0;
766 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000767 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000768 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000769 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000770 if (State.Stack.size() < State.StartOfLineLevel &&
771 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000772 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000773 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000774 }
775
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000776 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000777
Daniel Jasper2df93312013-01-09 10:16:05 +0000778 // Exceeding column limit is bad, assign penalty.
779 if (State.Column > getColumnLimit()) {
780 unsigned ExcessCharacters = State.Column - getColumnLimit();
781 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
782 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000783
Daniel Jasperf7935112012-12-03 18:12:45 +0000784 if (StopAt <= CurrentPenalty)
785 return UINT_MAX;
786 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000787 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000788 if (I != Memory.end()) {
789 // If this state has already been examined, we can safely return the
790 // previous result if we
791 // - have not hit the optimatization (and thus returned UINT_MAX) OR
792 // - are now computing for a smaller or equal StopAt.
793 unsigned SavedResult = I->second.first;
794 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000795 if (SavedResult != UINT_MAX)
796 return SavedResult + CurrentPenalty;
797 else if (StopAt <= SavedStopAt)
798 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000799 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000800
801 unsigned NoBreak = calcPenalty(State, false, StopAt);
802 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
803 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000804
805 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
806 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000807 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000808
809 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 }
811
Daniel Jasperf7935112012-12-03 18:12:45 +0000812 FormatStyle Style;
813 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000814 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000815 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000816 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000817 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000818
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000819 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000820 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000821 StateMap Memory;
822
Daniel Jasperf7935112012-12-03 18:12:45 +0000823 OptimizationParameters Parameters;
824};
825
826/// \brief Determines extra information about the tokens comprising an
827/// \c UnwrappedLine.
828class TokenAnnotator {
829public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000830 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
831 AnnotatedLine &Line)
832 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000833
834 /// \brief A parser that gathers additional information about tokens.
835 ///
836 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
837 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
838 /// into template parameter lists.
839 class AnnotatingParser {
840 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000841 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000842 : CurrentToken(&RootToken), KeywordVirtualFound(false),
843 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000844
Nico Weber250fe712013-01-18 02:43:57 +0000845 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
846 struct ObjCSelectorRAII {
847 AnnotatingParser &P;
848 bool ColonWasObjCMethodExpr;
849
850 ObjCSelectorRAII(AnnotatingParser &P)
851 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
852
853 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
854
855 void markStart(AnnotatedToken &Left) {
856 P.ColonIsObjCMethodExpr = true;
857 Left.Type = TT_ObjCMethodExpr;
858 }
859
860 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
861 };
862
863
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000864 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000865 if (CurrentToken == NULL)
866 return false;
867 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000868 while (CurrentToken != NULL) {
869 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000870 Left->MatchingParen = CurrentToken;
871 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000872 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000873 next();
874 return true;
875 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000876 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
877 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000878 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000879 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
880 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000881 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000882 if (!consumeToken())
883 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000884 }
885 return false;
886 }
887
Nico Weber80a82762013-01-17 17:17:19 +0000888 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000889 if (CurrentToken == NULL)
890 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000891 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000892 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000893 if (CurrentToken->is(tok::caret)) {
894 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000895 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000896 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
897 // @selector( starts a selector.
898 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
899 MaybeSel->Parent->is(tok::at)) {
900 StartsObjCMethodExpr = true;
901 }
902 }
903
904 ObjCSelectorRAII objCSelector(*this);
905 if (StartsObjCMethodExpr)
906 objCSelector.markStart(*Left);
907
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000908 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000909 // LookForDecls is set when "if (" has been seen. Check for
910 // 'identifier' '*' 'identifier' followed by not '=' -- this
911 // '*' has to be a binary operator but determineStarAmpUsage() will
912 // categorize it as an unary operator, so set the right type here.
913 if (LookForDecls && !CurrentToken->Children.empty()) {
914 AnnotatedToken &Prev = *CurrentToken->Parent;
915 AnnotatedToken &Next = CurrentToken->Children[0];
916 if (Prev.Parent->is(tok::identifier) &&
917 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
918 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
919 Prev.Type = TT_BinaryOperator;
920 LookForDecls = false;
921 }
922 }
923
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000924 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000925 Left->MatchingParen = CurrentToken;
926 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000927
928 if (StartsObjCMethodExpr)
929 objCSelector.markEnd(*CurrentToken);
930
Daniel Jasperf7935112012-12-03 18:12:45 +0000931 next();
932 return true;
933 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000934 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000935 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000936 if (!consumeToken())
937 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000938 }
939 return false;
940 }
941
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000942 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000943 if (!CurrentToken)
944 return false;
945
946 // A '[' could be an index subscript (after an indentifier or after
947 // ')' or ']'), or it could be the start of an Objective-C method
948 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000949 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000950 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000951 !Left->Parent || Left->Parent->is(tok::colon) ||
952 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
953 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
954 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000955 true, true) > prec::Unknown;
956
Nico Weber250fe712013-01-18 02:43:57 +0000957 ObjCSelectorRAII objCSelector(*this);
958 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000959 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000960
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 while (CurrentToken != NULL) {
962 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000963 if (!CurrentToken->Children.empty() &&
964 CurrentToken->Children[0].is(tok::l_paren)) {
965 // An ObjC method call can't be followed by an open parenthesis.
966 // FIXME: Do we incorrectly label ":" with this?
967 StartsObjCMethodExpr = false;
968 Left->Type = TT_Unknown;
969 }
Nico Weber250fe712013-01-18 02:43:57 +0000970 if (StartsObjCMethodExpr)
971 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000972 Left->MatchingParen = CurrentToken;
973 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000974 next();
975 return true;
976 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000977 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000978 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000979 if (!consumeToken())
980 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 }
982 return false;
983 }
984
Daniel Jasper83a54d22013-01-10 09:26:47 +0000985 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000986 // Lines are fine to end with '{'.
987 if (CurrentToken == NULL)
988 return true;
989 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000990 while (CurrentToken != NULL) {
991 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000992 Left->MatchingParen = CurrentToken;
993 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000994 next();
995 return true;
996 }
997 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
998 return false;
999 if (!consumeToken())
1000 return false;
1001 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001002 return true;
1003 }
1004
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001005 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001006 while (CurrentToken != NULL) {
1007 if (CurrentToken->is(tok::colon)) {
1008 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001009 next();
1010 return true;
1011 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001012 if (!consumeToken())
1013 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001014 }
1015 return false;
1016 }
1017
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001018 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001019 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1020 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001021 next();
1022 if (!parseAngle())
1023 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001024 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001025 return true;
1026 }
1027 return false;
1028 }
1029
Daniel Jasperc0880a92013-01-04 18:52:56 +00001030 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001032 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001033 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001034 case tok::plus:
1035 case tok::minus:
1036 // At the start of the line, +/- specific ObjectiveC method
1037 // declarations.
1038 if (Tok->Parent == NULL)
1039 Tok->Type = TT_ObjCMethodSpecifier;
1040 break;
Nico Webera7252d82013-01-12 06:18:40 +00001041 case tok::colon:
1042 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001043 if (Tok->Parent->is(tok::r_paren))
1044 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001045 if (ColonIsObjCMethodExpr)
1046 Tok->Type = TT_ObjCMethodExpr;
1047 break;
Nico Weber80a82762013-01-17 17:17:19 +00001048 case tok::kw_if:
1049 case tok::kw_while:
1050 if (CurrentToken->is(tok::l_paren)) {
1051 next();
1052 if (!parseParens(/*LookForDecls=*/true))
1053 return false;
1054 }
1055 break;
Nico Webera5510af2013-01-18 05:50:57 +00001056 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001057 if (!parseParens())
1058 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001059 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001060 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001061 if (!parseSquare())
1062 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001063 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001064 case tok::l_brace:
1065 if (!parseBrace())
1066 return false;
1067 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001068 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001069 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001070 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001072 Tok->Type = TT_BinaryOperator;
1073 CurrentToken = Tok;
1074 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001075 }
1076 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001077 case tok::r_paren:
1078 case tok::r_square:
1079 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001080 case tok::r_brace:
1081 // Lines can start with '}'.
1082 if (Tok->Parent != NULL)
1083 return false;
1084 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001085 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001086 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001087 break;
1088 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001089 if (CurrentToken->is(tok::l_paren)) {
1090 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001091 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001092 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1093 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001094 next();
1095 }
1096 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001097 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1098 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001099 next();
1100 }
1101 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001102 break;
1103 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001104 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001105 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001106 case tok::kw_template:
1107 parseTemplateDeclaration();
1108 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001109 default:
1110 break;
1111 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001112 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001113 }
1114
Daniel Jasper050948a52012-12-21 17:58:39 +00001115 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001116 next();
1117 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1118 next();
1119 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001120 if (CurrentToken->isNot(tok::comment) ||
1121 !CurrentToken->Children.empty())
1122 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001123 next();
1124 }
1125 } else {
1126 while (CurrentToken != NULL) {
1127 next();
1128 }
1129 }
1130 }
1131
1132 void parseWarningOrError() {
1133 next();
1134 // We still want to format the whitespace left of the first token of the
1135 // warning or error.
1136 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001137 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001138 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001139 next();
1140 }
1141 }
1142
1143 void parsePreprocessorDirective() {
1144 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001145 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001146 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001147 // Hashes in the middle of a line can lead to any strange token
1148 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001149 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001150 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 switch (
1152 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001153 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001154 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001155 parseIncludeDirective();
1156 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001157 case tok::pp_error:
1158 case tok::pp_warning:
1159 parseWarningOrError();
1160 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001161 default:
1162 break;
1163 }
1164 }
1165
Daniel Jasperda16db32013-01-07 10:48:50 +00001166 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001167 int PeriodsAndArrows = 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001168 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001169 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001170 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001171 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001172 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001173
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001174 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001175 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001176 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1177 ++PeriodsAndArrows;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001178 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001179 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001180 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001181 if (KeywordVirtualFound)
1182 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001183
1184 // Assume a builder-type call if there are 2 or more "." and "->".
1185 if (PeriodsAndArrows >= 2)
1186 return LT_BuilderTypeCall;
1187
Daniel Jasperda16db32013-01-07 10:48:50 +00001188 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001189 }
1190
1191 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001192 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1193 CurrentToken = &CurrentToken->Children[0];
1194 else
1195 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001196 }
1197
1198 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001199 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001200 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001201 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001202 };
1203
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001204 void calculateExtraInformation(AnnotatedToken &Current) {
1205 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1206
Manuel Klimek52b15152013-01-09 15:25:02 +00001207 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001208 Current.MustBreakBefore = true;
1209 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001210 if (Current.Type == TT_LineComment) {
1211 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001212 } else if ((Current.Parent->is(tok::comment) &&
1213 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001214 (Current.is(tok::string_literal) &&
1215 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001216 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001217 } else {
1218 Current.MustBreakBefore = false;
1219 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001220 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001221 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001222 if (Current.MustBreakBefore)
1223 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1224 else
1225 Current.TotalLength = Current.Parent->TotalLength +
1226 Current.FormatTok.TokenLength +
1227 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001228 if (!Current.Children.empty())
1229 calculateExtraInformation(Current.Children[0]);
1230 }
1231
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001232 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001233 AnnotatingParser Parser(Line.First);
1234 Line.Type = Parser.parseLine();
1235 if (Line.Type == LT_Invalid)
1236 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001237
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001238 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001239
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001240 if (Line.First.Type == TT_ObjCMethodSpecifier)
1241 Line.Type = LT_ObjCMethodDecl;
1242 else if (Line.First.Type == TT_ObjCDecl)
1243 Line.Type = LT_ObjCDecl;
1244 else if (Line.First.Type == TT_ObjCProperty)
1245 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001246
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001247 Line.First.SpaceRequiredBefore = true;
1248 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1249 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001250
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001251 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001252 if (!Line.First.Children.empty())
1253 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 }
1255
1256private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001257 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1258 if (getPrecedence(Current) == prec::Assignment ||
1259 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1260 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001261
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001262 if (Current.Type == TT_Unknown) {
1263 if (Current.is(tok::star) || Current.is(tok::amp)) {
1264 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001265 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1266 Current.is(tok::caret)) {
1267 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001268 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1269 Current.Type = determineIncrementUsage(Current);
1270 } else if (Current.is(tok::exclaim)) {
1271 Current.Type = TT_UnaryOperator;
1272 } else if (isBinaryOperator(Current)) {
1273 Current.Type = TT_BinaryOperator;
1274 } else if (Current.is(tok::comment)) {
1275 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1276 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001277 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001278 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001279 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001280 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001281 } else if (Current.is(tok::r_paren) &&
1282 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001283 Current.Parent->Type == TT_TemplateCloser) &&
1284 (Current.Children.empty() ||
1285 (Current.Children[0].isNot(tok::equal) &&
1286 Current.Children[0].isNot(tok::semi) &&
1287 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001288 // FIXME: We need to get smarter and understand more cases of casts.
1289 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001290 } else if (Current.is(tok::at) && Current.Children.size()) {
1291 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1292 case tok::objc_interface:
1293 case tok::objc_implementation:
1294 case tok::objc_protocol:
1295 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001296 break;
1297 case tok::objc_property:
1298 Current.Type = TT_ObjCProperty;
1299 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001300 default:
1301 break;
1302 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001303 }
1304 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001305
1306 if (!Current.Children.empty())
1307 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001308 }
1309
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001310 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001311 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001312 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001313 }
1314
Daniel Jasper71945272013-01-15 14:27:39 +00001315 /// \brief Returns the previous token ignoring comments.
1316 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1317 const AnnotatedToken *PrevToken = Tok.Parent;
1318 while (PrevToken != NULL && PrevToken->is(tok::comment))
1319 PrevToken = PrevToken->Parent;
1320 return PrevToken;
1321 }
1322
1323 /// \brief Returns the next token ignoring comments.
1324 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1325 if (Tok.Children.empty())
1326 return NULL;
1327 const AnnotatedToken *NextToken = &Tok.Children[0];
1328 while (NextToken->is(tok::comment)) {
1329 if (NextToken->Children.empty())
1330 return NULL;
1331 NextToken = &NextToken->Children[0];
1332 }
1333 return NextToken;
1334 }
1335
1336 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001337 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001338 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1339 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001340 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001341
1342 const AnnotatedToken *NextToken = getNextToken(Tok);
1343 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001344 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001345
Daniel Jasper0b820602013-01-22 11:46:26 +00001346 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1347 return TT_PointerOrReference;
1348
Daniel Jasper71945272013-01-15 14:27:39 +00001349 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1350 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1351 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1352 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001353 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001354 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001355
Daniel Jasper71945272013-01-15 14:27:39 +00001356 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1357 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1358 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1359 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1360 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1361 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1362 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001363 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001364
Daniel Jasper71945272013-01-15 14:27:39 +00001365 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1366 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001367 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001368
Daniel Jasper426702d2012-12-05 07:51:39 +00001369 // It is very unlikely that we are going to find a pointer or reference type
1370 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001371 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001372 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001373
Daniel Jasperda16db32013-01-07 10:48:50 +00001374 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001375 }
1376
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001377 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001378 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1379 if (PrevToken == NULL)
1380 return TT_UnaryOperator;
1381
Daniel Jasper8dd40472012-12-21 09:41:31 +00001382 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001383 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1384 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1385 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1386 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1387 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001388 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001389
1390 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001391 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001392 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001393
1394 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001395 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001396 }
1397
1398 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001399 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001400 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1401 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001402 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001403 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1404 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001405 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001406
Daniel Jasperda16db32013-01-07 10:48:50 +00001407 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001408 }
1409
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001410 bool spaceRequiredBetween(const AnnotatedToken &Left,
1411 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001412 if (Right.is(tok::hashhash))
1413 return Left.is(tok::hash);
1414 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1415 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001416 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1417 return false;
Nico Webera6087752013-01-10 20:12:55 +00001418 if (Right.is(tok::less) &&
1419 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001420 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001421 return true;
1422 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1423 return false;
1424 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1425 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001426 if (Left.is(tok::at) &&
1427 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1428 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001429 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1430 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001431 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001432 if (Left.is(tok::coloncolon))
1433 return false;
1434 if (Right.is(tok::coloncolon))
1435 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001436 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1437 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001438 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001439 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001440 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1441 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001442 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001443 return Right.FormatTok.Tok.isLiteral() ||
1444 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001445 if (Right.is(tok::star) && Left.is(tok::l_paren))
1446 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001447 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1448 return false;
1449 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001450 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001451 if (Left.is(tok::period) || Right.is(tok::period))
1452 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001453 if (Left.is(tok::colon))
1454 return Left.Type != TT_ObjCMethodExpr;
1455 if (Right.is(tok::colon))
1456 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001457 if (Left.is(tok::l_paren))
1458 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001459 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001460 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001461 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001462 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001463 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1464 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001465 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001466 if (Left.is(tok::at) &&
1467 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001468 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001469 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1470 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001471 return true;
1472 }
1473
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001474 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001475 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001476 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1477 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001478 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001479 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001480 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001481 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001482 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001483 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001484 // Don't space between ')' and <id>
1485 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001486 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001487 // Don't space between ':' and '('
1488 return false;
1489 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001490 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001491 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1492 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001493
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001494 if (Tok.Parent->is(tok::comma))
1495 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001496 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001497 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001498 if (Tok.Type == TT_OverloadedOperator)
1499 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001500 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001501 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001502 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001503 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001504 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001505 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001506 if (Tok.Parent->Type == TT_UnaryOperator ||
1507 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001508 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001509 if (Tok.Type == TT_UnaryOperator)
1510 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001511 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1512 (Tok.Parent->isNot(tok::colon) ||
1513 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001514 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1515 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001516 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1517 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001518 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001519 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001520 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001521 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001522 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001523 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001524 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001525 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001526 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001527 }
1528
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001529 bool canBreakBefore(const AnnotatedToken &Right) {
1530 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001531 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001532 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1533 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001534 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001535 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1536 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001537 // Don't break this identifier as ':' or identifier
1538 // before it will break.
1539 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001540 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1541 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001542 // Don't break at ':' if identifier before it can beak.
1543 return false;
1544 }
Nico Webera7252d82013-01-12 06:18:40 +00001545 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1546 return false;
1547 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1548 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001549 if (isObjCSelectorName(Right))
1550 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001551 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001552 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001553 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001554 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001555 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001556 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001557 return false;
1558
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001559 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001560 // We rely on MustBreakBefore being set correctly here as we should not
1561 // change the "binding" behavior of a comment.
1562 return false;
1563
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001564 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1565 // unless it is follow by ';', '{' or '='.
1566 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1567 Left.Parent->is(tok::r_paren))
1568 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1569 Right.isNot(tok::equal);
1570
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001571 // We only break before r_brace if there was a corresponding break before
1572 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1573 if (Right.is(tok::r_brace))
1574 return false;
1575
Daniel Jasper71945272013-01-15 14:27:39 +00001576 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001577 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001578 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1579 Left.is(tok::comma) || Right.is(tok::lessless) ||
1580 Right.is(tok::arrow) || Right.is(tok::period) ||
1581 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001582 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1583 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1584 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001585 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001586 }
1587
Daniel Jasperf7935112012-12-03 18:12:45 +00001588 FormatStyle Style;
1589 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001590 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001591 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001592};
1593
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001594class LexerBasedFormatTokenSource : public FormatTokenSource {
1595public:
1596 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001597 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001598 IdentTable(Lex.getLangOpts()) {
1599 Lex.SetKeepWhitespaceMode(true);
1600 }
1601
1602 virtual FormatToken getNextToken() {
1603 if (GreaterStashed) {
1604 FormatTok.NewlinesBefore = 0;
1605 FormatTok.WhiteSpaceStart =
1606 FormatTok.Tok.getLocation().getLocWithOffset(1);
1607 FormatTok.WhiteSpaceLength = 0;
1608 GreaterStashed = false;
1609 return FormatTok;
1610 }
1611
1612 FormatTok = FormatToken();
1613 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001614 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001615 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001616 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1617 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001618
1619 // Consume and record whitespace until we find a significant token.
1620 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001621 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001622 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1623 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001624 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1625
1626 if (FormatTok.Tok.is(tok::eof))
1627 return FormatTok;
1628 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001629 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001630 }
Manuel Klimekef920692013-01-07 07:56:50 +00001631
1632 // Now FormatTok is the next non-whitespace token.
1633 FormatTok.TokenLength = Text.size();
1634
Manuel Klimek1abf7892013-01-04 23:34:14 +00001635 // In case the token starts with escaped newlines, we want to
1636 // take them into account as whitespace - this pattern is quite frequent
1637 // in macro definitions.
1638 // FIXME: What do we want to do with other escaped spaces, and escaped
1639 // spaces or newlines in the middle of tokens?
1640 // FIXME: Add a more explicit test.
1641 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001642 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001643 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001644 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001645 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001646 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001647 }
1648
1649 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001650 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001651 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001652 FormatTok.Tok.setKind(Info.getTokenID());
1653 }
1654
1655 if (FormatTok.Tok.is(tok::greatergreater)) {
1656 FormatTok.Tok.setKind(tok::greater);
1657 GreaterStashed = true;
1658 }
1659
1660 return FormatTok;
1661 }
1662
1663private:
1664 FormatToken FormatTok;
1665 bool GreaterStashed;
1666 Lexer &Lex;
1667 SourceManager &SourceMgr;
1668 IdentifierTable IdentTable;
1669
1670 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001671 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001672 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1673 Tok.getLength());
1674 }
1675};
1676
Daniel Jasperf7935112012-12-03 18:12:45 +00001677class Formatter : public UnwrappedLineConsumer {
1678public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001679 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1680 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001681 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001682 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001683 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001684
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001685 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001686
Daniel Jasperf7935112012-12-03 18:12:45 +00001687 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001688 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001689 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001690 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001691 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001692 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1693 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1694 Annotator.annotate();
1695 }
1696 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1697 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001698 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001699 const AnnotatedLine &TheLine = *I;
1700 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1701 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1702 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001703 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001704 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001705 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001706 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001707 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001708 PreviousEndOfLineColumn = Formatter.format();
1709 } else {
1710 // If we did not reformat this unwrapped line, the column at the end of
1711 // the last token is unchanged - thus, we can calculate the end of the
1712 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001713 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001714 SourceMgr.getSpellingColumnNumber(
1715 TheLine.Last->FormatTok.Tok.getLocation()) +
1716 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1717 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001718 1;
1719 }
1720 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001721 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001722 }
1723
1724private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001725 /// \brief Tries to merge lines into one.
1726 ///
1727 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1728 /// if possible; note that \c I will be incremented when lines are merged.
1729 ///
1730 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001731 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001732 std::vector<AnnotatedLine>::iterator &I,
1733 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001734 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1735
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001736 // We can never merge stuff if there are trailing line comments.
1737 if (I->Last->Type == TT_LineComment)
1738 return;
1739
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001740 // Check whether the UnwrappedLine can be put onto a single line. If
1741 // so, this is bound to be the optimal solution (by definition) and we
1742 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001743 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001744 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001745 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001746
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001747 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001748 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001749
Daniel Jasper25837aa2013-01-14 14:14:23 +00001750 if (I->Last->is(tok::l_brace)) {
1751 tryMergeSimpleBlock(I, E, Limit);
1752 } else if (I->First.is(tok::kw_if)) {
1753 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001754 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1755 I->First.FormatTok.IsFirst)) {
1756 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001757 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001758 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001759 }
1760
Daniel Jasper39825ea2013-01-14 15:40:57 +00001761 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1762 std::vector<AnnotatedLine>::iterator E,
1763 unsigned Limit) {
1764 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001765 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1766 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001767 if (I + 2 != E && (I + 2)->InPPDirective &&
1768 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1769 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001770 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001771 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001772 join(Line, *(++I));
1773 }
1774
Daniel Jasper25837aa2013-01-14 14:14:23 +00001775 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1776 std::vector<AnnotatedLine>::iterator E,
1777 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001778 if (!Style.AllowShortIfStatementsOnASingleLine)
1779 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001780 if ((I + 1)->InPPDirective != I->InPPDirective ||
1781 ((I + 1)->InPPDirective &&
1782 (I + 1)->First.FormatTok.HasUnescapedNewline))
1783 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001784 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001785 if (Line.Last->isNot(tok::r_paren))
1786 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001787 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001788 return;
1789 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1790 return;
1791 // Only inline simple if's (no nested if or else).
1792 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1793 return;
1794 join(Line, *(++I));
1795 }
1796
1797 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1798 std::vector<AnnotatedLine>::iterator E,
1799 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001800 // First, check that the current line allows merging. This is the case if
1801 // we're not in a control flow statement and the last token is an opening
1802 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001803 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001804 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001805 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1806 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1807 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1808 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001809 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001810 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1811 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001812 if (!AllowedTokens)
1813 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001814
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001815 AnnotatedToken *Tok = &(I + 1)->First;
1816 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1817 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1818 Tok->SpaceRequiredBefore = false;
1819 join(Line, *(I + 1));
1820 I += 1;
1821 } else {
1822 // Check that we still have three lines and they fit into the limit.
1823 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1824 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001825 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001826
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001827 // Second, check that the next line does not contain any braces - if it
1828 // does, readability declines when putting it into a single line.
1829 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1830 return;
1831 do {
1832 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1833 return;
1834 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1835 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001836
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001837 // Last, check that the third line contains a single closing brace.
1838 Tok = &(I + 2)->First;
1839 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1840 Tok->MustBreakBefore)
1841 return;
1842
1843 join(Line, *(I + 1));
1844 join(Line, *(I + 2));
1845 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001846 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001847 }
1848
1849 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1850 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001851 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1852 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001853 }
1854
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001855 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1856 A.Last->Children.push_back(B.First);
1857 while (!A.Last->Children.empty()) {
1858 A.Last->Children[0].Parent = A.Last;
1859 A.Last = &A.Last->Children[0];
1860 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001861 }
1862
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001863 bool touchesRanges(const AnnotatedLine &TheLine) {
1864 const FormatToken *First = &TheLine.First.FormatTok;
1865 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001866 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001867 First->Tok.getLocation(),
1868 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001869 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001870 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1871 Ranges[i].getBegin()) &&
1872 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1873 LineRange.getBegin()))
1874 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001875 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001876 return false;
1877 }
1878
1879 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001880 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001881 }
1882
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001883 /// \brief Add a new line and the required indent before the first Token
1884 /// of the \c UnwrappedLine if there was no structural parsing error.
1885 /// Returns the indent level of the \c UnwrappedLine.
1886 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1887 bool InPPDirective,
1888 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001889 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001890 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1891 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1892
1893 unsigned Newlines = std::min(Tok.NewlinesBefore,
1894 Style.MaxEmptyLinesToKeep + 1);
1895 if (Newlines == 0 && !Tok.IsFirst)
1896 Newlines = 1;
1897 unsigned Indent = Level * 2;
1898
1899 bool IsAccessModifier = false;
1900 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1901 RootToken.is(tok::kw_private))
1902 IsAccessModifier = true;
1903 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1904 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1905 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1906 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1907 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1908 IsAccessModifier = true;
1909
1910 if (IsAccessModifier &&
1911 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1912 Indent += Style.AccessModifierOffset;
1913 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001914 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001915 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001916 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1917 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001918 }
1919 return Indent;
1920 }
1921
Alexander Kornienko116ba682013-01-14 11:34:14 +00001922 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001923 FormatStyle Style;
1924 Lexer &Lex;
1925 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001926 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001927 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001928 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001929 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001930};
1931
1932tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1933 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001934 std::vector<CharSourceRange> Ranges,
1935 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001936 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001937 OwningPtr<DiagnosticConsumer> DiagPrinter;
1938 if (DiagClient == 0) {
1939 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1940 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1941 DiagClient = DiagPrinter.get();
1942 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001943 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001944 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001945 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001946 Diagnostics.setSourceManager(&SourceMgr);
1947 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001948 return formatter.format();
1949}
1950
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001951LangOptions getFormattingLangOpts() {
1952 LangOptions LangOpts;
1953 LangOpts.CPlusPlus = 1;
1954 LangOpts.CPlusPlus11 = 1;
1955 LangOpts.Bool = 1;
1956 LangOpts.ObjC1 = 1;
1957 LangOpts.ObjC2 = 1;
1958 return LangOpts;
1959}
1960
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001961} // namespace format
1962} // namespace clang