blob: 50df593d85f912ea93409680f662e59d69d18af6 [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,
63 LT_PreprocessorDirective,
64 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000065 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000066 LT_ObjCMethodDecl,
67 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000068};
69
Daniel Jasper7c85fde2013-01-08 14:56:18 +000070class AnnotatedToken {
71public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000072 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000073 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
74 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper9278eb92013-01-16 14:59:02 +000075 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000076
Daniel Jasper25837aa2013-01-14 14:14:23 +000077 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
78 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
79
Daniel Jasper7c85fde2013-01-08 14:56:18 +000080 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
81 return FormatTok.Tok.isObjCAtKeyword(Kind);
82 }
83
84 FormatToken FormatTok;
85
Daniel Jasperf7935112012-12-03 18:12:45 +000086 TokenType Type;
87
Daniel Jasperf7935112012-12-03 18:12:45 +000088 bool SpaceRequiredBefore;
89 bool CanBreakBefore;
90 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000091
92 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000093
Daniel Jasper9278eb92013-01-16 14:59:02 +000094 AnnotatedToken *MatchingParen;
95
Daniel Jaspera67a8f02013-01-16 10:41:46 +000096 /// \brief The total length of the line up to and including this token.
97 unsigned TotalLength;
98
Daniel Jasper7c85fde2013-01-08 14:56:18 +000099 std::vector<AnnotatedToken> Children;
100 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000101
102 const AnnotatedToken *getPreviousNoneComment() const {
103 AnnotatedToken *Tok = Parent;
104 while (Tok != NULL && Tok->is(tok::comment))
105 Tok = Tok->Parent;
106 return Tok;
107 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000108};
109
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000110class AnnotatedLine {
111public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000112 AnnotatedLine(const UnwrappedLine &Line)
113 : First(Line.Tokens.front()), Level(Line.Level),
114 InPPDirective(Line.InPPDirective) {
115 assert(!Line.Tokens.empty());
116 AnnotatedToken *Current = &First;
117 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
118 E = Line.Tokens.end();
119 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000121 Current->Children[0].Parent = Current;
122 Current = &Current->Children[0];
123 }
124 Last = Current;
125 }
126 AnnotatedLine(const AnnotatedLine &Other)
127 : First(Other.First), Type(Other.Type), Level(Other.Level),
128 InPPDirective(Other.InPPDirective) {
129 Last = &First;
130 while (!Last->Children.empty()) {
131 Last->Children[0].Parent = Last;
132 Last = &Last->Children[0];
133 }
134 }
135
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000136 AnnotatedToken First;
137 AnnotatedToken *Last;
138
139 LineType Type;
140 unsigned Level;
141 bool InPPDirective;
142};
143
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000144static prec::Level getPrecedence(const AnnotatedToken &Tok) {
145 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000146}
147
Daniel Jasperf7935112012-12-03 18:12:45 +0000148FormatStyle getLLVMStyle() {
149 FormatStyle LLVMStyle;
150 LLVMStyle.ColumnLimit = 80;
151 LLVMStyle.MaxEmptyLinesToKeep = 1;
152 LLVMStyle.PointerAndReferenceBindToType = false;
153 LLVMStyle.AccessModifierOffset = -2;
154 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000155 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000156 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000157 LLVMStyle.BinPackParameters = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000158 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000160 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000161 return LLVMStyle;
162}
163
164FormatStyle getGoogleStyle() {
165 FormatStyle GoogleStyle;
166 GoogleStyle.ColumnLimit = 80;
167 GoogleStyle.MaxEmptyLinesToKeep = 1;
168 GoogleStyle.PointerAndReferenceBindToType = true;
169 GoogleStyle.AccessModifierOffset = -1;
170 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000171 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000172 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000173 GoogleStyle.BinPackParameters = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000174 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000175 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000176 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000177 return GoogleStyle;
178}
179
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000180FormatStyle getChromiumStyle() {
181 FormatStyle ChromiumStyle = getGoogleStyle();
182 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
183 return ChromiumStyle;
184}
185
Daniel Jasperf7935112012-12-03 18:12:45 +0000186struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000187 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000188 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000189 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000190};
191
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000192/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000193///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000194/// This includes special handling for certain constructs, e.g. the alignment of
195/// trailing line comments.
196class WhitespaceManager {
197public:
198 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
199
200 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
201 /// each \c AnnotatedToken.
202 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
203 unsigned Spaces, unsigned WhitespaceStartColumn,
204 const FormatStyle &Style) {
205 if (Tok.Type == TT_LineComment && NewLines < 2 &&
206 (Tok.Parent != NULL || !Comments.empty())) {
207 if (Style.ColumnLimit >=
208 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
209 Comments.push_back(StoredComment());
210 Comments.back().Tok = Tok.FormatTok;
211 Comments.back().Spaces = Spaces;
212 Comments.back().NewLines = NewLines;
213 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
214 Comments.back().MaxColumn = Style.ColumnLimit -
215 Spaces - Tok.FormatTok.TokenLength;
216 return;
217 }
218 } else if (NewLines == 0 && Tok.Children.empty() &&
219 Tok.Type != TT_LineComment) {
220 alignComments();
221 }
222 storeReplacement(Tok.FormatTok,
223 std::string(NewLines, '\n') + std::string(Spaces, ' '));
224 }
225
226 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
227 /// backslashes to escape newlines inside a preprocessor directive.
228 ///
229 /// This function and \c replaceWhitespace have the same behavior if
230 /// \c Newlines == 0.
231 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
232 unsigned Spaces, unsigned WhitespaceStartColumn,
233 const FormatStyle &Style) {
234 std::string NewLineText;
235 if (NewLines > 0) {
236 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
237 WhitespaceStartColumn);
238 for (unsigned i = 0; i < NewLines; ++i) {
239 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
240 NewLineText += "\\\n";
241 Offset = 0;
242 }
243 }
244 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
245 }
246
247 /// \brief Returns all the \c Replacements created during formatting.
248 const tooling::Replacements &generateReplacements() {
249 alignComments();
250 return Replaces;
251 }
252
253private:
254 /// \brief Structure to store a comment for later layout and alignment.
255 struct StoredComment {
256 FormatToken Tok;
257 unsigned MinColumn;
258 unsigned MaxColumn;
259 unsigned NewLines;
260 unsigned Spaces;
261 };
262 SmallVector<StoredComment, 16> Comments;
263 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
264
265 /// \brief Try to align all stashed comments.
266 void alignComments() {
267 unsigned MinColumn = 0;
268 unsigned MaxColumn = UINT_MAX;
269 comment_iterator Start = Comments.begin();
270 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
271 ++I) {
272 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
273 alignComments(Start, I, MinColumn);
274 MinColumn = I->MinColumn;
275 MaxColumn = I->MaxColumn;
276 Start = I;
277 } else {
278 MinColumn = std::max(MinColumn, I->MinColumn);
279 MaxColumn = std::min(MaxColumn, I->MaxColumn);
280 }
281 }
282 alignComments(Start, Comments.end(), MinColumn);
283 Comments.clear();
284 }
285
286 /// \brief Put all the comments between \p I and \p E into \p Column.
287 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
288 while (I != E) {
289 unsigned Spaces = I->Spaces + Column - I->MinColumn;
290 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
291 std::string(Spaces, ' '));
292 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000293 }
294 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000295
296 /// \brief Stores \p Text as the replacement for the whitespace in front of
297 /// \p Tok.
298 void storeReplacement(const FormatToken &Tok, const std::string Text) {
299 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
300 Tok.WhiteSpaceLength, Text));
301 }
302
303 SourceManager &SourceMgr;
304 tooling::Replacements Replaces;
305};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000306
Nico Weberc9d73612013-01-12 22:48:47 +0000307/// \brief Returns if a token is an Objective-C selector name.
308///
Nico Weber92c05392013-01-12 22:51:13 +0000309/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000310static bool isObjCSelectorName(const AnnotatedToken &Tok) {
311 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
312 Tok.Children[0].is(tok::colon) &&
313 Tok.Children[0].Type == TT_ObjCMethodExpr;
314}
315
Daniel Jasperf7935112012-12-03 18:12:45 +0000316class UnwrappedLineFormatter {
317public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000318 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000319 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000320 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000321 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000322 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000323 FirstIndent(FirstIndent), RootToken(RootToken),
324 Whitespaces(Whitespaces) {
Daniel Jasperde5c2072012-12-24 00:13:23 +0000325 Parameters.PenaltyIndentLevel = 15;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000326 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000327 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 }
329
Manuel Klimek1abf7892013-01-04 23:34:14 +0000330 /// \brief Formats an \c UnwrappedLine.
331 ///
332 /// \returns The column after the last token in the last line of the
333 /// \c UnwrappedLine.
334 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000335 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000336 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000337 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000338 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000339 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000340 State.ForLoopVariablePos = 0;
341 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000342 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000343
Manuel Klimek24998102013-01-16 14:55:28 +0000344 DEBUG({
345 DebugTokenState(*State.NextToken);
346 });
347
Daniel Jaspere9de2602012-12-06 09:56:08 +0000348 // The first token has already been indented and thus consumed.
349 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000350
351 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000352 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000353 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
354 // Calculating the column is important for aligning trailing comments.
355 // FIXME: This does not seem to happen in conjunction with escaped
356 // newlines. If it does, fix!
357 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
358 State.NextToken->FormatTok.TokenLength;
359 State.NextToken = State.NextToken->Children.empty() ? NULL :
360 &State.NextToken->Children[0];
361 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000362 addTokenToState(false, false, State);
363 } else {
364 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
365 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000366 DEBUG({
367 if (Break < NoBreak)
368 llvm::errs() << "\n";
369 else
370 llvm::errs() << " ";
371 llvm::errs() << "<";
372 DebugPenalty(Break, Break < NoBreak);
373 llvm::errs() << "/";
374 DebugPenalty(NoBreak, !(Break < NoBreak));
375 llvm::errs() << "> ";
376 DebugTokenState(*State.NextToken);
377 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000378 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000379 if (State.NextToken != NULL &&
380 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
381 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000382 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000383 State.Stack.back().BreakAfterComma = true;
384 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000385 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000386 }
Manuel Klimek24998102013-01-16 14:55:28 +0000387 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000388 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000389 }
390
391private:
Manuel Klimek24998102013-01-16 14:55:28 +0000392 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
393 const Token &Tok = AnnotatedTok.FormatTok.Tok;
394 llvm::errs()
395 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
396 Tok.getLength());
397 llvm::errs();
398 }
399
400 void DebugPenalty(unsigned Penalty, bool Winner) {
401 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
402 if (Penalty == UINT_MAX)
403 llvm::errs() << "MAX";
404 else
405 llvm::errs() << Penalty;
406 llvm::errs().resetColor();
407 }
408
Daniel Jasper337816e2013-01-11 10:22:12 +0000409 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000410 ParenState(unsigned Indent, unsigned LastSpace)
411 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000412 BreakBeforeClosingBrace(false), BreakAfterComma(false),
413 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000414
Daniel Jasperf7935112012-12-03 18:12:45 +0000415 /// \brief The position to which a specific parenthesis level needs to be
416 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000417 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000418
Daniel Jaspere9de2602012-12-06 09:56:08 +0000419 /// \brief The position of the last space on each level.
420 ///
421 /// Used e.g. to break like:
422 /// functionCall(Parameter, otherCall(
423 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jaspere9de2602012-12-06 09:56:08 +0000426 /// \brief The position the first "<<" operator encountered on each level.
427 ///
428 /// Used to align "<<" operators. 0 if no such operator has been encountered
429 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000430 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000431
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000432 /// \brief Whether a newline needs to be inserted before the block's closing
433 /// brace.
434 ///
435 /// We only want to insert a newline before the closing brace if there also
436 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 bool BreakBeforeClosingBrace;
438
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000439 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000440 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000441
Daniel Jasper337816e2013-01-11 10:22:12 +0000442 bool operator<(const ParenState &Other) const {
443 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000444 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000445 if (LastSpace != Other.LastSpace)
446 return LastSpace < Other.LastSpace;
447 if (FirstLessLess != Other.FirstLessLess)
448 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000449 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
450 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000451 if (BreakAfterComma != Other.BreakAfterComma)
452 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000453 if (HasMultiParameterLine != Other.HasMultiParameterLine)
454 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000455 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000456 }
457 };
458
459 /// \brief The current state when indenting a unwrapped line.
460 ///
461 /// As the indenting tries different combinations this is copied by value.
462 struct LineState {
463 /// \brief The number of used columns in the current line.
464 unsigned Column;
465
466 /// \brief The token that needs to be next formatted.
467 const AnnotatedToken *NextToken;
468
469 /// \brief The parenthesis level of the first token on the current line.
470 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000471
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000472 /// \brief The column of the first variable in a for-loop declaration.
473 ///
474 /// Used to align the second variable if necessary.
475 unsigned ForLoopVariablePos;
476
477 /// \brief \c true if this line contains a continued for-loop section.
478 bool LineContainsContinuedForLoopSection;
479
Daniel Jasper337816e2013-01-11 10:22:12 +0000480 /// \brief A stack keeping track of properties applying to parenthesis
481 /// levels.
482 std::vector<ParenState> Stack;
483
484 /// \brief Comparison operator to be able to used \c LineState in \c map.
485 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000486 if (Other.NextToken != NextToken)
487 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000488 if (Other.Column != Column)
489 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000490 if (Other.StartOfLineLevel != StartOfLineLevel)
491 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000492 if (Other.ForLoopVariablePos != ForLoopVariablePos)
493 return Other.ForLoopVariablePos < ForLoopVariablePos;
494 if (Other.LineContainsContinuedForLoopSection !=
495 LineContainsContinuedForLoopSection)
496 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000497 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000498 }
499 };
500
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000501 /// \brief Appends the next token to \p State and updates information
502 /// necessary for indentation.
503 ///
504 /// Puts the token on the current line if \p Newline is \c true and adds a
505 /// line break and necessary indentation otherwise.
506 ///
507 /// If \p DryRun is \c false, also creates and stores the required
508 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000509 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000510 const AnnotatedToken &Current = *State.NextToken;
511 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000512 assert(State.Stack.size());
513 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000514
515 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000516 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000517 if (Current.is(tok::r_brace)) {
518 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000519 } else if (Current.is(tok::string_literal) &&
520 Previous.is(tok::string_literal)) {
521 State.Column = State.Column - Previous.FormatTok.TokenLength;
522 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000523 State.Stack[ParenLevel].FirstLessLess != 0) {
524 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000525 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000526 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
527 Current.is(tok::period) || Previous.is(tok::question) ||
528 Previous.Type == TT_ConditionalExpr)) {
529 // Indent and extra 4 spaces after if we know the current expression is
530 // continued. Don't do that on the top level, as we already indent 4
531 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000532 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000534 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000535 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000536 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000537 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000538 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000539 }
540
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000541 // A line starting with a closing brace is assumed to be correct for the
542 // same level as before the opening brace.
543 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000544
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000545 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000546 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000547
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000548 if (!DryRun) {
549 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000550 Whitespaces.replaceWhitespace(Current, 1, State.Column,
551 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000552 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000553 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
554 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000555 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000556
Daniel Jasper337816e2013-01-11 10:22:12 +0000557 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000558 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000560 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000561 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
562 State.ForLoopVariablePos = State.Column -
563 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000564
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000565 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
566 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000567 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000568
Daniel Jasperf7935112012-12-03 18:12:45 +0000569 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000570 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000571
Daniel Jasperbcab4302013-01-09 10:40:23 +0000572 // FIXME: Do we need to do this for assignments nested in other
573 // expressions?
574 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000575 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000576 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000577 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000578 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000579 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000580 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000581 if (Current.getPreviousNoneComment()->is(tok::comma) &&
582 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000583 State.Stack[ParenLevel].HasMultiParameterLine = true;
584
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000585
Daniel Jasper206df732013-01-07 13:08:40 +0000586 // Top-level spaces that are not part of assignments are exempt as that
587 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000588 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000589 if (Spaces > 0 &&
590 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000591 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000592 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000593
594 // If we break after an {, we should also break before the corresponding }.
595 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000596 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000597
598 // If we are breaking after '(', '{', '<' or ',', we need to break after
599 // future commas as well to avoid bin packing.
600 if (!Style.BinPackParameters && Newline &&
601 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
602 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
603 State.Stack.back().BreakAfterComma = true;
604
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000605 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000606 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000607
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000608 /// \brief Mark the next token as consumed in \p State and modify its stacks
609 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000610 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000611 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000612 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000613
Daniel Jasper337816e2013-01-11 10:22:12 +0000614 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
615 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000616
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000617 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000618 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000619 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
620 Current.is(tok::l_brace) ||
621 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000622 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000623 if (Current.is(tok::l_brace)) {
624 // FIXME: This does not work with nested static initializers.
625 // Implement a better handling for static initializers and similar
626 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000627 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000628 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000629 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000630 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000631 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000632 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000633
634 // If the entire set of parameters will not fit on the current line, we
635 // will need to break after commas on this level to avoid bin-packing.
636 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
637 !Current.Children.empty()) {
638 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
639 Current.MatchingParen->TotalLength -
640 Current.Children[0].TotalLength) {
641 State.Stack.back().BreakAfterComma = true;
642 }
643 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000644 }
645
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000646 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000647 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000648 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
649 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
650 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000651 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000652 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000653
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000654 if (State.NextToken->Children.empty())
655 State.NextToken = NULL;
656 else
657 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000658
659 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000660 }
661
Nico Weber49cbc2c2013-01-07 15:15:29 +0000662 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000663 unsigned splitPenalty(const AnnotatedToken &Tok) {
664 const AnnotatedToken &Left = Tok;
665 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000666
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000667 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
668 return 50;
669 if (Left.is(tok::equal) && Right.is(tok::l_brace))
670 return 150;
671
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000672 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000673 if (RootToken.is(tok::kw_for) &&
674 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000675 return 20;
676
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000677 if (Left.is(tok::semi) || Left.is(tok::comma) ||
678 Left.ClosesTemplateDeclaration)
Daniel Jasperf7935112012-12-03 18:12:45 +0000679 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000680
681 // In Objective-C method expressions, prefer breaking before "param:" over
682 // breaking after it.
683 if (isObjCSelectorName(Right))
684 return 0;
685 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
686 return 20;
687
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000688 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000689 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000690
Daniel Jasper399d24b2013-01-09 07:06:56 +0000691 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
692 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000693 prec::Level Level = getPrecedence(Left);
694
695 // Breaking after an assignment leads to a bad result as the two sides of
696 // the assignment are visually very close together.
697 if (Level == prec::Assignment)
698 return 50;
699
Daniel Jasperde5c2072012-12-24 00:13:23 +0000700 if (Level != prec::Unknown)
701 return Level;
702
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000703 if (Right.is(tok::arrow) || Right.is(tok::period))
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000704 return 150;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000705
Daniel Jasperf7935112012-12-03 18:12:45 +0000706 return 3;
707 }
708
Daniel Jasper2df93312013-01-09 10:16:05 +0000709 unsigned getColumnLimit() {
710 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
711 }
712
Daniel Jasperf7935112012-12-03 18:12:45 +0000713 /// \brief Calculate the number of lines needed to format the remaining part
714 /// of the unwrapped line.
715 ///
716 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000717 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000718 /// added after the previous token.
719 ///
720 /// \param StopAt is used for optimization. If we can determine that we'll
721 /// definitely need at least \p StopAt additional lines, we already know of a
722 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000723 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000724 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000725 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000726 return 0;
727
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000728 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000729 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000730 if (NewLine && !State.NextToken->CanBreakBefore &&
731 !(State.NextToken->is(tok::r_brace) &&
732 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000734 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000735 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000736 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000737 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000738 State.LineContainsContinuedForLoopSection)
739 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000740 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000741 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000742 State.Stack.back().BreakAfterComma)
743 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000744 // Trying to insert a parameter on a new line if there are already more than
745 // one parameter on the current line is bin packing.
746 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
747 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
748 return UINT_MAX;
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000749 if (!NewLine && State.NextToken->Type == TT_CtorInitializerColon)
750 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000751
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000752 unsigned CurrentPenalty = 0;
753 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000754 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000755 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000756 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000757 if (State.Stack.size() < State.StartOfLineLevel &&
758 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000759 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000760 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000761 }
762
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000763 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000764
Daniel Jasper2df93312013-01-09 10:16:05 +0000765 // Exceeding column limit is bad, assign penalty.
766 if (State.Column > getColumnLimit()) {
767 unsigned ExcessCharacters = State.Column - getColumnLimit();
768 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
769 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000770
Daniel Jasperf7935112012-12-03 18:12:45 +0000771 if (StopAt <= CurrentPenalty)
772 return UINT_MAX;
773 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000774 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000775 if (I != Memory.end()) {
776 // If this state has already been examined, we can safely return the
777 // previous result if we
778 // - have not hit the optimatization (and thus returned UINT_MAX) OR
779 // - are now computing for a smaller or equal StopAt.
780 unsigned SavedResult = I->second.first;
781 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000782 if (SavedResult != UINT_MAX)
783 return SavedResult + CurrentPenalty;
784 else if (StopAt <= SavedStopAt)
785 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000786 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000787
788 unsigned NoBreak = calcPenalty(State, false, StopAt);
789 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
790 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000791
792 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
793 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000794 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000795
796 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000797 }
798
Daniel Jasperf7935112012-12-03 18:12:45 +0000799 FormatStyle Style;
800 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000801 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000802 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000803 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000804 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000805
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000806 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000807 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000808 StateMap Memory;
809
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 OptimizationParameters Parameters;
811};
812
813/// \brief Determines extra information about the tokens comprising an
814/// \c UnwrappedLine.
815class TokenAnnotator {
816public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000817 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
818 AnnotatedLine &Line)
819 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000820
821 /// \brief A parser that gathers additional information about tokens.
822 ///
823 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
824 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
825 /// into template parameter lists.
826 class AnnotatingParser {
827 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000828 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000829 : CurrentToken(&RootToken), KeywordVirtualFound(false),
830 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000831
Nico Weber250fe712013-01-18 02:43:57 +0000832 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
833 struct ObjCSelectorRAII {
834 AnnotatingParser &P;
835 bool ColonWasObjCMethodExpr;
836
837 ObjCSelectorRAII(AnnotatingParser &P)
838 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
839
840 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
841
842 void markStart(AnnotatedToken &Left) {
843 P.ColonIsObjCMethodExpr = true;
844 Left.Type = TT_ObjCMethodExpr;
845 }
846
847 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
848 };
849
850
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000851 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000852 if (CurrentToken == NULL)
853 return false;
854 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000855 while (CurrentToken != NULL) {
856 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000857 Left->MatchingParen = CurrentToken;
858 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000859 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000860 next();
861 return true;
862 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000863 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
864 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000865 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000866 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
867 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000868 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000869 if (!consumeToken())
870 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000871 }
872 return false;
873 }
874
Nico Weber80a82762013-01-17 17:17:19 +0000875 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000876 if (CurrentToken == NULL)
877 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000878 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000879 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000880 if (CurrentToken->is(tok::caret)) {
881 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000882 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000883 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
884 // @selector( starts a selector.
885 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
886 MaybeSel->Parent->is(tok::at)) {
887 StartsObjCMethodExpr = true;
888 }
889 }
890
891 ObjCSelectorRAII objCSelector(*this);
892 if (StartsObjCMethodExpr)
893 objCSelector.markStart(*Left);
894
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000895 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000896 // LookForDecls is set when "if (" has been seen. Check for
897 // 'identifier' '*' 'identifier' followed by not '=' -- this
898 // '*' has to be a binary operator but determineStarAmpUsage() will
899 // categorize it as an unary operator, so set the right type here.
900 if (LookForDecls && !CurrentToken->Children.empty()) {
901 AnnotatedToken &Prev = *CurrentToken->Parent;
902 AnnotatedToken &Next = CurrentToken->Children[0];
903 if (Prev.Parent->is(tok::identifier) &&
904 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
905 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
906 Prev.Type = TT_BinaryOperator;
907 LookForDecls = false;
908 }
909 }
910
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000911 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000912 Left->MatchingParen = CurrentToken;
913 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000914
915 if (StartsObjCMethodExpr)
916 objCSelector.markEnd(*CurrentToken);
917
Daniel Jasperf7935112012-12-03 18:12:45 +0000918 next();
919 return true;
920 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000921 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000922 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000923 if (!consumeToken())
924 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000925 }
926 return false;
927 }
928
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000929 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000930 if (!CurrentToken)
931 return false;
932
933 // A '[' could be an index subscript (after an indentifier or after
934 // ')' or ']'), or it could be the start of an Objective-C method
935 // expression.
936 AnnotatedToken *LSquare = CurrentToken->Parent;
937 bool StartsObjCMethodExpr =
938 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
939 LSquare->Parent->is(tok::l_square) ||
940 LSquare->Parent->is(tok::l_paren) ||
941 LSquare->Parent->is(tok::kw_return) ||
942 LSquare->Parent->is(tok::kw_throw) ||
943 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
944 true, true) > prec::Unknown;
945
Nico Weber250fe712013-01-18 02:43:57 +0000946 ObjCSelectorRAII objCSelector(*this);
947 if (StartsObjCMethodExpr)
948 objCSelector.markStart(*LSquare);
Nico Webera7252d82013-01-12 06:18:40 +0000949
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000950 while (CurrentToken != NULL) {
951 if (CurrentToken->is(tok::r_square)) {
Nico Weber250fe712013-01-18 02:43:57 +0000952 if (StartsObjCMethodExpr)
953 objCSelector.markEnd(*CurrentToken);
Daniel Jasperf7935112012-12-03 18:12:45 +0000954 next();
955 return true;
956 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000957 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000959 if (!consumeToken())
960 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 }
962 return false;
963 }
964
Daniel Jasper83a54d22013-01-10 09:26:47 +0000965 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000966 // Lines are fine to end with '{'.
967 if (CurrentToken == NULL)
968 return true;
969 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000970 while (CurrentToken != NULL) {
971 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000972 Left->MatchingParen = CurrentToken;
973 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000974 next();
975 return true;
976 }
977 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
978 return false;
979 if (!consumeToken())
980 return false;
981 }
Daniel Jasper83a54d22013-01-10 09:26:47 +0000982 return true;
983 }
984
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000985 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000986 while (CurrentToken != NULL) {
987 if (CurrentToken->is(tok::colon)) {
988 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000989 next();
990 return true;
991 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000992 if (!consumeToken())
993 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000994 }
995 return false;
996 }
997
Daniel Jasperac5c1c22013-01-02 15:08:56 +0000998 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000999 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1000 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001001 next();
1002 if (!parseAngle())
1003 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001004 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001005 parseLine();
1006 return true;
1007 }
1008 return false;
1009 }
1010
Daniel Jasperc0880a92013-01-04 18:52:56 +00001011 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001012 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001013 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001014 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001015 case tok::plus:
1016 case tok::minus:
1017 // At the start of the line, +/- specific ObjectiveC method
1018 // declarations.
1019 if (Tok->Parent == NULL)
1020 Tok->Type = TT_ObjCMethodSpecifier;
1021 break;
Nico Webera7252d82013-01-12 06:18:40 +00001022 case tok::colon:
1023 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001024 if (Tok->Parent->is(tok::r_paren))
1025 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001026 if (ColonIsObjCMethodExpr)
1027 Tok->Type = TT_ObjCMethodExpr;
1028 break;
Nico Weber80a82762013-01-17 17:17:19 +00001029 case tok::kw_if:
1030 case tok::kw_while:
1031 if (CurrentToken->is(tok::l_paren)) {
1032 next();
1033 if (!parseParens(/*LookForDecls=*/true))
1034 return false;
1035 }
1036 break;
Nico Webera5510af2013-01-18 05:50:57 +00001037 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001038 if (!parseParens())
1039 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001040 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001041 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001042 if (!parseSquare())
1043 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001045 case tok::l_brace:
1046 if (!parseBrace())
1047 return false;
1048 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001049 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001050 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001051 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 Tok->Type = TT_BinaryOperator;
1054 CurrentToken = Tok;
1055 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001056 }
1057 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001058 case tok::r_paren:
1059 case tok::r_square:
1060 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001061 case tok::r_brace:
1062 // Lines can start with '}'.
1063 if (Tok->Parent != NULL)
1064 return false;
1065 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001067 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001068 break;
1069 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001070 if (CurrentToken->is(tok::l_paren)) {
1071 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001072 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001073 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1074 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001075 next();
1076 }
1077 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001078 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1079 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001080 next();
1081 }
1082 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 break;
1084 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001085 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001086 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001087 case tok::kw_template:
1088 parseTemplateDeclaration();
1089 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001090 default:
1091 break;
1092 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001093 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001094 }
1095
Daniel Jasper050948a52012-12-21 17:58:39 +00001096 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001097 next();
1098 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1099 next();
1100 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001101 if (CurrentToken->isNot(tok::comment) ||
1102 !CurrentToken->Children.empty())
1103 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001104 next();
1105 }
1106 } else {
1107 while (CurrentToken != NULL) {
1108 next();
1109 }
1110 }
1111 }
1112
1113 void parseWarningOrError() {
1114 next();
1115 // We still want to format the whitespace left of the first token of the
1116 // warning or error.
1117 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001118 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001119 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001120 next();
1121 }
1122 }
1123
1124 void parsePreprocessorDirective() {
1125 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001127 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001128 // Hashes in the middle of a line can lead to any strange token
1129 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001130 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001131 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001132 switch (
1133 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001134 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001135 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001136 parseIncludeDirective();
1137 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001138 case tok::pp_error:
1139 case tok::pp_warning:
1140 parseWarningOrError();
1141 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001142 default:
1143 break;
1144 }
1145 }
1146
Daniel Jasperda16db32013-01-07 10:48:50 +00001147 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001148 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001149 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001150 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001151 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001152 while (CurrentToken != NULL) {
1153 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001154 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001155 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001156 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001157 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001158 if (KeywordVirtualFound)
1159 return LT_VirtualFunctionDecl;
1160 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001161 }
1162
1163 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001164 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1165 CurrentToken = &CurrentToken->Children[0];
1166 else
1167 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001168 }
1169
1170 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001171 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001172 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001173 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001174 };
1175
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001176 void calculateExtraInformation(AnnotatedToken &Current) {
1177 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1178
Manuel Klimek52b15152013-01-09 15:25:02 +00001179 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001180 Current.MustBreakBefore = true;
1181 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001182 if (Current.Type == TT_LineComment) {
1183 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001184 } else if ((Current.Parent->is(tok::comment) &&
1185 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001186 (Current.is(tok::string_literal) &&
1187 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001188 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001189 } else {
1190 Current.MustBreakBefore = false;
1191 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001192 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001193 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001194 if (Current.MustBreakBefore)
1195 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1196 else
1197 Current.TotalLength = Current.Parent->TotalLength +
1198 Current.FormatTok.TokenLength +
1199 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001200 if (!Current.Children.empty())
1201 calculateExtraInformation(Current.Children[0]);
1202 }
1203
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001204 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001205 AnnotatingParser Parser(Line.First);
1206 Line.Type = Parser.parseLine();
1207 if (Line.Type == LT_Invalid)
1208 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001209
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001210 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001211
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001212 if (Line.First.Type == TT_ObjCMethodSpecifier)
1213 Line.Type = LT_ObjCMethodDecl;
1214 else if (Line.First.Type == TT_ObjCDecl)
1215 Line.Type = LT_ObjCDecl;
1216 else if (Line.First.Type == TT_ObjCProperty)
1217 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001218
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001219 Line.First.SpaceRequiredBefore = true;
1220 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1221 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001222
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001223 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001224 if (!Line.First.Children.empty())
1225 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001226 }
1227
1228private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001229 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1230 if (getPrecedence(Current) == prec::Assignment ||
1231 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1232 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001233
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001234 if (Current.Type == TT_Unknown) {
1235 if (Current.is(tok::star) || Current.is(tok::amp)) {
1236 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001237 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1238 Current.is(tok::caret)) {
1239 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001240 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1241 Current.Type = determineIncrementUsage(Current);
1242 } else if (Current.is(tok::exclaim)) {
1243 Current.Type = TT_UnaryOperator;
1244 } else if (isBinaryOperator(Current)) {
1245 Current.Type = TT_BinaryOperator;
1246 } else if (Current.is(tok::comment)) {
1247 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1248 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001249 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001250 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001251 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001252 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001253 } else if (Current.is(tok::r_paren) &&
1254 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001255 Current.Parent->Type == TT_TemplateCloser) &&
1256 (Current.Children.empty() ||
1257 (Current.Children[0].isNot(tok::equal) &&
1258 Current.Children[0].isNot(tok::semi) &&
1259 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001260 // FIXME: We need to get smarter and understand more cases of casts.
1261 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001262 } else if (Current.is(tok::at) && Current.Children.size()) {
1263 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1264 case tok::objc_interface:
1265 case tok::objc_implementation:
1266 case tok::objc_protocol:
1267 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001268 break;
1269 case tok::objc_property:
1270 Current.Type = TT_ObjCProperty;
1271 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001272 default:
1273 break;
1274 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001275 }
1276 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001277
1278 if (!Current.Children.empty())
1279 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001280 }
1281
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001282 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001283 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001284 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001285 }
1286
Daniel Jasper71945272013-01-15 14:27:39 +00001287 /// \brief Returns the previous token ignoring comments.
1288 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1289 const AnnotatedToken *PrevToken = Tok.Parent;
1290 while (PrevToken != NULL && PrevToken->is(tok::comment))
1291 PrevToken = PrevToken->Parent;
1292 return PrevToken;
1293 }
1294
1295 /// \brief Returns the next token ignoring comments.
1296 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1297 if (Tok.Children.empty())
1298 return NULL;
1299 const AnnotatedToken *NextToken = &Tok.Children[0];
1300 while (NextToken->is(tok::comment)) {
1301 if (NextToken->Children.empty())
1302 return NULL;
1303 NextToken = &NextToken->Children[0];
1304 }
1305 return NextToken;
1306 }
1307
1308 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001309 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001310 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1311 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001312 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001313
1314 const AnnotatedToken *NextToken = getNextToken(Tok);
1315 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001316 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001317
Daniel Jasper71945272013-01-15 14:27:39 +00001318 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1319 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1320 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1321 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001322 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001323 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001324
Daniel Jasper71945272013-01-15 14:27:39 +00001325 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1326 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1327 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1328 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1329 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1330 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1331 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001332 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001333
Daniel Jasper71945272013-01-15 14:27:39 +00001334 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1335 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001336 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001337
Daniel Jasper426702d2012-12-05 07:51:39 +00001338 // It is very unlikely that we are going to find a pointer or reference type
1339 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001340 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001341 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001342
Daniel Jasperda16db32013-01-07 10:48:50 +00001343 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001344 }
1345
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001346 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001347 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1348 if (PrevToken == NULL)
1349 return TT_UnaryOperator;
1350
Daniel Jasper8dd40472012-12-21 09:41:31 +00001351 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001352 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1353 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1354 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1355 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1356 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001357 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001358
1359 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001360 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001361 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001362
1363 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001364 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001365 }
1366
1367 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001368 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001369 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1370 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001371 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001372 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1373 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001374 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001375
Daniel Jasperda16db32013-01-07 10:48:50 +00001376 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001377 }
1378
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001379 bool spaceRequiredBetween(const AnnotatedToken &Left,
1380 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001381 if (Right.is(tok::hashhash))
1382 return Left.is(tok::hash);
1383 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1384 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001385 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1386 return false;
Nico Webera6087752013-01-10 20:12:55 +00001387 if (Right.is(tok::less) &&
1388 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001389 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001390 return true;
1391 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1392 return false;
1393 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1394 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001395 if (Left.is(tok::at) &&
1396 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1397 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001398 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1399 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001400 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001401 if (Left.is(tok::coloncolon))
1402 return false;
1403 if (Right.is(tok::coloncolon))
1404 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001405 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1406 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001407 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001408 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001409 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1410 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001411 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001412 return Right.FormatTok.Tok.isLiteral() ||
1413 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001414 if (Right.is(tok::star) && Left.is(tok::l_paren))
1415 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001416 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1417 return false;
1418 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001419 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001420 if (Left.is(tok::period) || Right.is(tok::period))
1421 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001422 if (Left.is(tok::colon))
1423 return Left.Type != TT_ObjCMethodExpr;
1424 if (Right.is(tok::colon))
1425 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001426 if (Left.is(tok::l_paren))
1427 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001428 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001429 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001430 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001431 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001432 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1433 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001434 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001435 if (Left.is(tok::at) &&
1436 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001437 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001438 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1439 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001440 return true;
1441 }
1442
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001443 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001444 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001445 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1446 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001447 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001448 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001449 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001450 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001451 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001452 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001453 // Don't space between ')' and <id>
1454 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001455 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001456 // Don't space between ':' and '('
1457 return false;
1458 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001459 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001460 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1461 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001462
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001463 if (Tok.Parent->is(tok::comma))
1464 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001465 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001466 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001467 if (Tok.Type == TT_OverloadedOperator)
1468 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001469 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001470 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001471 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001472 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001473 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001474 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001475 if (Tok.Parent->Type == TT_UnaryOperator ||
1476 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001477 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001478 if (Tok.Type == TT_UnaryOperator)
1479 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001480 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1481 (Tok.Parent->isNot(tok::colon) ||
1482 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001483 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1484 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001485 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1486 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001487 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001488 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001489 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001490 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001491 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001492 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001493 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001494 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001495 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001496 }
1497
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001498 bool canBreakBefore(const AnnotatedToken &Right) {
1499 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001500 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001501 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1502 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001503 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001504 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1505 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001506 // Don't break this identifier as ':' or identifier
1507 // before it will break.
1508 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001509 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1510 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001511 // Don't break at ':' if identifier before it can beak.
1512 return false;
1513 }
Nico Webera7252d82013-01-12 06:18:40 +00001514 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1515 return false;
1516 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1517 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001518 if (isObjCSelectorName(Right))
1519 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001520 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001521 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001522 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001523 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001524 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001525 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001526 return false;
1527
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001528 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001529 // We rely on MustBreakBefore being set correctly here as we should not
1530 // change the "binding" behavior of a comment.
1531 return false;
1532
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001533 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1534 // unless it is follow by ';', '{' or '='.
1535 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1536 Left.Parent->is(tok::r_paren))
1537 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1538 Right.isNot(tok::equal);
1539
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001540 // We only break before r_brace if there was a corresponding break before
1541 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1542 if (Right.is(tok::r_brace))
1543 return false;
1544
Daniel Jasper71945272013-01-15 14:27:39 +00001545 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001546 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001547 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1548 Left.is(tok::comma) || Right.is(tok::lessless) ||
1549 Right.is(tok::arrow) || Right.is(tok::period) ||
1550 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001551 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1552 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1553 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001554 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001555 }
1556
Daniel Jasperf7935112012-12-03 18:12:45 +00001557 FormatStyle Style;
1558 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001559 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001560 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001561};
1562
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001563class LexerBasedFormatTokenSource : public FormatTokenSource {
1564public:
1565 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001566 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001567 IdentTable(Lex.getLangOpts()) {
1568 Lex.SetKeepWhitespaceMode(true);
1569 }
1570
1571 virtual FormatToken getNextToken() {
1572 if (GreaterStashed) {
1573 FormatTok.NewlinesBefore = 0;
1574 FormatTok.WhiteSpaceStart =
1575 FormatTok.Tok.getLocation().getLocWithOffset(1);
1576 FormatTok.WhiteSpaceLength = 0;
1577 GreaterStashed = false;
1578 return FormatTok;
1579 }
1580
1581 FormatTok = FormatToken();
1582 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001583 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001584 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001585 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1586 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001587
1588 // Consume and record whitespace until we find a significant token.
1589 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001590 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001591 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1592 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001593 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1594
1595 if (FormatTok.Tok.is(tok::eof))
1596 return FormatTok;
1597 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001598 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001599 }
Manuel Klimekef920692013-01-07 07:56:50 +00001600
1601 // Now FormatTok is the next non-whitespace token.
1602 FormatTok.TokenLength = Text.size();
1603
Manuel Klimek1abf7892013-01-04 23:34:14 +00001604 // In case the token starts with escaped newlines, we want to
1605 // take them into account as whitespace - this pattern is quite frequent
1606 // in macro definitions.
1607 // FIXME: What do we want to do with other escaped spaces, and escaped
1608 // spaces or newlines in the middle of tokens?
1609 // FIXME: Add a more explicit test.
1610 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001611 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001612 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001613 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001614 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001615 }
1616
1617 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001618 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001619 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001620 FormatTok.Tok.setKind(Info.getTokenID());
1621 }
1622
1623 if (FormatTok.Tok.is(tok::greatergreater)) {
1624 FormatTok.Tok.setKind(tok::greater);
1625 GreaterStashed = true;
1626 }
1627
1628 return FormatTok;
1629 }
1630
1631private:
1632 FormatToken FormatTok;
1633 bool GreaterStashed;
1634 Lexer &Lex;
1635 SourceManager &SourceMgr;
1636 IdentifierTable IdentTable;
1637
1638 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001639 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001640 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1641 Tok.getLength());
1642 }
1643};
1644
Daniel Jasperf7935112012-12-03 18:12:45 +00001645class Formatter : public UnwrappedLineConsumer {
1646public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001647 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1648 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001649 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001650 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001651 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001652
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001653 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001654
Daniel Jasperf7935112012-12-03 18:12:45 +00001655 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001656 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001657 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001658 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001659 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001660 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1661 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1662 Annotator.annotate();
1663 }
1664 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1665 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001666 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001667 const AnnotatedLine &TheLine = *I;
1668 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1669 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1670 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001671 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001672 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001673 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001674 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001675 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001676 PreviousEndOfLineColumn = Formatter.format();
1677 } else {
1678 // If we did not reformat this unwrapped line, the column at the end of
1679 // the last token is unchanged - thus, we can calculate the end of the
1680 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001681 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001682 SourceMgr.getSpellingColumnNumber(
1683 TheLine.Last->FormatTok.Tok.getLocation()) +
1684 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1685 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001686 1;
1687 }
1688 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001689 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001690 }
1691
1692private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001693 /// \brief Tries to merge lines into one.
1694 ///
1695 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1696 /// if possible; note that \c I will be incremented when lines are merged.
1697 ///
1698 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001699 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001700 std::vector<AnnotatedLine>::iterator &I,
1701 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001702 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1703
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001704 // We can never merge stuff if there are trailing line comments.
1705 if (I->Last->Type == TT_LineComment)
1706 return;
1707
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001708 // Check whether the UnwrappedLine can be put onto a single line. If
1709 // so, this is bound to be the optimal solution (by definition) and we
1710 // don't need to analyze the entire solution space.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001711 if (I->Last->TotalLength >= Limit)
1712 return;
1713 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasperc36492b2013-01-16 07:02:34 +00001714
Daniel Jasper25837aa2013-01-14 14:14:23 +00001715 if (I + 1 == E)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001716 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001717
Daniel Jasper25837aa2013-01-14 14:14:23 +00001718 if (I->Last->is(tok::l_brace)) {
1719 tryMergeSimpleBlock(I, E, Limit);
1720 } else if (I->First.is(tok::kw_if)) {
1721 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001722 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1723 I->First.FormatTok.IsFirst)) {
1724 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001725 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001726 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001727 }
1728
Daniel Jasper39825ea2013-01-14 15:40:57 +00001729 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1730 std::vector<AnnotatedLine>::iterator E,
1731 unsigned Limit) {
1732 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001733 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1734 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001735 if (I + 2 != E && (I + 2)->InPPDirective &&
1736 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1737 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001738 if ((I + 1)->Last->TotalLength > Limit)
1739 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001740 join(Line, *(++I));
1741 }
1742
Daniel Jasper25837aa2013-01-14 14:14:23 +00001743 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1744 std::vector<AnnotatedLine>::iterator E,
1745 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001746 if (!Style.AllowShortIfStatementsOnASingleLine)
1747 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001748 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001749 if (Line.Last->isNot(tok::r_paren))
1750 return;
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001751 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001752 return;
1753 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1754 return;
1755 // Only inline simple if's (no nested if or else).
1756 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1757 return;
1758 join(Line, *(++I));
1759 }
1760
1761 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1762 std::vector<AnnotatedLine>::iterator E,
1763 unsigned Limit){
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001764 // Check that we still have three lines and they fit into the limit.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001765 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1766 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001767
1768 // First, check that the current line allows merging. This is the case if
1769 // we're not in a control flow statement and the last token is an opening
1770 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001771 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001772 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001773 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1774 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1775 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1776 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001777 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001778 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1779 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001780 if (!AllowedTokens)
1781 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001782
1783 // Second, check that the next line does not contain any braces - if it
1784 // does, readability declines when putting it into a single line.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001785 const AnnotatedToken *Tok = &(I + 1)->First;
1786 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001787 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001788 do {
1789 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001790 return;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001791 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1792 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001793
1794 // Last, check that the third line contains a single closing brace.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001795 Tok = &(I + 2)->First;
1796 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1797 Tok->MustBreakBefore)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001798 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001799
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001800 // If the merged line fits, we use that instead and skip the next two lines.
1801 Line.Last->Children.push_back((I + 1)->First);
1802 while (!Line.Last->Children.empty()) {
1803 Line.Last->Children[0].Parent = Line.Last;
1804 Line.Last = &Line.Last->Children[0];
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001805 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001806
1807 join(Line, *(I + 1));
1808 join(Line, *(I + 2));
1809 I += 2;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001810 }
1811
1812 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1813 unsigned Limit) {
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001814 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001815 }
1816
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001817 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1818 A.Last->Children.push_back(B.First);
1819 while (!A.Last->Children.empty()) {
1820 A.Last->Children[0].Parent = A.Last;
1821 A.Last = &A.Last->Children[0];
1822 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001823 }
1824
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001825 bool touchesRanges(const AnnotatedLine &TheLine) {
1826 const FormatToken *First = &TheLine.First.FormatTok;
1827 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001828 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001829 First->Tok.getLocation(),
1830 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001831 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001832 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1833 Ranges[i].getBegin()) &&
1834 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1835 LineRange.getBegin()))
1836 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001837 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001838 return false;
1839 }
1840
1841 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001842 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001843 }
1844
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001845 /// \brief Add a new line and the required indent before the first Token
1846 /// of the \c UnwrappedLine if there was no structural parsing error.
1847 /// Returns the indent level of the \c UnwrappedLine.
1848 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1849 bool InPPDirective,
1850 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001851 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001852 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1853 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1854
1855 unsigned Newlines = std::min(Tok.NewlinesBefore,
1856 Style.MaxEmptyLinesToKeep + 1);
1857 if (Newlines == 0 && !Tok.IsFirst)
1858 Newlines = 1;
1859 unsigned Indent = Level * 2;
1860
1861 bool IsAccessModifier = false;
1862 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1863 RootToken.is(tok::kw_private))
1864 IsAccessModifier = true;
1865 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1866 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1867 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1868 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1869 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1870 IsAccessModifier = true;
1871
1872 if (IsAccessModifier &&
1873 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1874 Indent += Style.AccessModifierOffset;
1875 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001876 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001877 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001878 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1879 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001880 }
1881 return Indent;
1882 }
1883
Alexander Kornienko116ba682013-01-14 11:34:14 +00001884 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001885 FormatStyle Style;
1886 Lexer &Lex;
1887 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001888 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001889 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001890 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001891 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001892};
1893
1894tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1895 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001896 std::vector<CharSourceRange> Ranges,
1897 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001898 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001899 OwningPtr<DiagnosticConsumer> DiagPrinter;
1900 if (DiagClient == 0) {
1901 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1902 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1903 DiagClient = DiagPrinter.get();
1904 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001905 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001906 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001907 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001908 Diagnostics.setSourceManager(&SourceMgr);
1909 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001910 return formatter.format();
1911}
1912
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001913LangOptions getFormattingLangOpts() {
1914 LangOptions LangOpts;
1915 LangOpts.CPlusPlus = 1;
1916 LangOpts.CPlusPlus11 = 1;
1917 LangOpts.Bool = 1;
1918 LangOpts.ObjC1 = 1;
1919 LangOpts.ObjC2 = 1;
1920 return LangOpts;
1921}
1922
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001923} // namespace format
1924} // namespace clang