blob: 7c25cbb0594385c246d78df77d9580ad97072a4c [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 Jasper04468962013-01-18 10:56:38 +0000325 Parameters.PenaltyIndentLevel = 20;
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 Jasper04468962013-01-18 10:56:38 +0000677 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000678 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000679
680 // In Objective-C method expressions, prefer breaking before "param:" over
681 // breaking after it.
682 if (isObjCSelectorName(Right))
683 return 0;
684 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
685 return 20;
686
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000687 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000688 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000689
Daniel Jasper399d24b2013-01-09 07:06:56 +0000690 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
691 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000692 prec::Level Level = getPrecedence(Left);
693
694 // Breaking after an assignment leads to a bad result as the two sides of
695 // the assignment are visually very close together.
696 if (Level == prec::Assignment)
697 return 50;
698
Daniel Jasperde5c2072012-12-24 00:13:23 +0000699 if (Level != prec::Unknown)
700 return Level;
701
Daniel Jasper04468962013-01-18 10:56:38 +0000702 if (Right.is(tok::arrow) || Right.is(tok::period)) {
703 if (Left.is(tok::r_paren))
704 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000705 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000706 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000707
Daniel Jasperf7935112012-12-03 18:12:45 +0000708 return 3;
709 }
710
Daniel Jasper2df93312013-01-09 10:16:05 +0000711 unsigned getColumnLimit() {
712 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
713 }
714
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 /// \brief Calculate the number of lines needed to format the remaining part
716 /// of the unwrapped line.
717 ///
718 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000719 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000720 /// added after the previous token.
721 ///
722 /// \param StopAt is used for optimization. If we can determine that we'll
723 /// definitely need at least \p StopAt additional lines, we already know of a
724 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000725 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000726 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000727 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000728 return 0;
729
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000730 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000731 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000732 if (NewLine && !State.NextToken->CanBreakBefore &&
733 !(State.NextToken->is(tok::r_brace) &&
734 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000736 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000737 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000738 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000739 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000740 State.LineContainsContinuedForLoopSection)
741 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000742 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000743 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000744 State.Stack.back().BreakAfterComma)
745 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000746 // Trying to insert a parameter on a new line if there are already more than
747 // one parameter on the current line is bin packing.
748 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
749 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
750 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000751 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
752 (State.NextToken->Parent->ClosesTemplateDeclaration &&
753 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000754 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000755
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000756 unsigned CurrentPenalty = 0;
757 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000758 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000759 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000760 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000761 if (State.Stack.size() < State.StartOfLineLevel &&
762 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000763 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000764 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000765 }
766
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000767 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000768
Daniel Jasper2df93312013-01-09 10:16:05 +0000769 // Exceeding column limit is bad, assign penalty.
770 if (State.Column > getColumnLimit()) {
771 unsigned ExcessCharacters = State.Column - getColumnLimit();
772 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
773 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000774
Daniel Jasperf7935112012-12-03 18:12:45 +0000775 if (StopAt <= CurrentPenalty)
776 return UINT_MAX;
777 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000778 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000779 if (I != Memory.end()) {
780 // If this state has already been examined, we can safely return the
781 // previous result if we
782 // - have not hit the optimatization (and thus returned UINT_MAX) OR
783 // - are now computing for a smaller or equal StopAt.
784 unsigned SavedResult = I->second.first;
785 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000786 if (SavedResult != UINT_MAX)
787 return SavedResult + CurrentPenalty;
788 else if (StopAt <= SavedStopAt)
789 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000790 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000791
792 unsigned NoBreak = calcPenalty(State, false, StopAt);
793 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
794 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000795
796 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
797 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000798 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000799
800 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000801 }
802
Daniel Jasperf7935112012-12-03 18:12:45 +0000803 FormatStyle Style;
804 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000805 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000806 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000807 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000808 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000809
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000810 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000811 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000812 StateMap Memory;
813
Daniel Jasperf7935112012-12-03 18:12:45 +0000814 OptimizationParameters Parameters;
815};
816
817/// \brief Determines extra information about the tokens comprising an
818/// \c UnwrappedLine.
819class TokenAnnotator {
820public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000821 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
822 AnnotatedLine &Line)
823 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000824
825 /// \brief A parser that gathers additional information about tokens.
826 ///
827 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
828 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
829 /// into template parameter lists.
830 class AnnotatingParser {
831 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000832 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000833 : CurrentToken(&RootToken), KeywordVirtualFound(false),
834 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000835
Nico Weber250fe712013-01-18 02:43:57 +0000836 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
837 struct ObjCSelectorRAII {
838 AnnotatingParser &P;
839 bool ColonWasObjCMethodExpr;
840
841 ObjCSelectorRAII(AnnotatingParser &P)
842 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
843
844 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
845
846 void markStart(AnnotatedToken &Left) {
847 P.ColonIsObjCMethodExpr = true;
848 Left.Type = TT_ObjCMethodExpr;
849 }
850
851 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
852 };
853
854
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000855 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000856 if (CurrentToken == NULL)
857 return false;
858 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000859 while (CurrentToken != NULL) {
860 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000861 Left->MatchingParen = CurrentToken;
862 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000863 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000864 next();
865 return true;
866 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000867 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
868 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000869 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
871 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000872 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000873 if (!consumeToken())
874 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000875 }
876 return false;
877 }
878
Nico Weber80a82762013-01-17 17:17:19 +0000879 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000880 if (CurrentToken == NULL)
881 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000882 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000883 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000884 if (CurrentToken->is(tok::caret)) {
885 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000886 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000887 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
888 // @selector( starts a selector.
889 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
890 MaybeSel->Parent->is(tok::at)) {
891 StartsObjCMethodExpr = true;
892 }
893 }
894
895 ObjCSelectorRAII objCSelector(*this);
896 if (StartsObjCMethodExpr)
897 objCSelector.markStart(*Left);
898
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000899 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000900 // LookForDecls is set when "if (" has been seen. Check for
901 // 'identifier' '*' 'identifier' followed by not '=' -- this
902 // '*' has to be a binary operator but determineStarAmpUsage() will
903 // categorize it as an unary operator, so set the right type here.
904 if (LookForDecls && !CurrentToken->Children.empty()) {
905 AnnotatedToken &Prev = *CurrentToken->Parent;
906 AnnotatedToken &Next = CurrentToken->Children[0];
907 if (Prev.Parent->is(tok::identifier) &&
908 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
909 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
910 Prev.Type = TT_BinaryOperator;
911 LookForDecls = false;
912 }
913 }
914
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000915 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000916 Left->MatchingParen = CurrentToken;
917 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000918
919 if (StartsObjCMethodExpr)
920 objCSelector.markEnd(*CurrentToken);
921
Daniel Jasperf7935112012-12-03 18:12:45 +0000922 next();
923 return true;
924 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000925 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000926 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000927 if (!consumeToken())
928 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 }
930 return false;
931 }
932
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000933 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000934 if (!CurrentToken)
935 return false;
936
937 // A '[' could be an index subscript (after an indentifier or after
938 // ')' or ']'), or it could be the start of an Objective-C method
939 // expression.
940 AnnotatedToken *LSquare = CurrentToken->Parent;
941 bool StartsObjCMethodExpr =
942 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
943 LSquare->Parent->is(tok::l_square) ||
944 LSquare->Parent->is(tok::l_paren) ||
945 LSquare->Parent->is(tok::kw_return) ||
946 LSquare->Parent->is(tok::kw_throw) ||
947 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
948 true, true) > prec::Unknown;
949
Nico Weber250fe712013-01-18 02:43:57 +0000950 ObjCSelectorRAII objCSelector(*this);
951 if (StartsObjCMethodExpr)
952 objCSelector.markStart(*LSquare);
Nico Webera7252d82013-01-12 06:18:40 +0000953
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000954 while (CurrentToken != NULL) {
955 if (CurrentToken->is(tok::r_square)) {
Nico Weber250fe712013-01-18 02:43:57 +0000956 if (StartsObjCMethodExpr)
957 objCSelector.markEnd(*CurrentToken);
Daniel Jasperf7935112012-12-03 18:12:45 +0000958 next();
959 return true;
960 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000961 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000962 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000963 if (!consumeToken())
964 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 }
966 return false;
967 }
968
Daniel Jasper83a54d22013-01-10 09:26:47 +0000969 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000970 // Lines are fine to end with '{'.
971 if (CurrentToken == NULL)
972 return true;
973 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000974 while (CurrentToken != NULL) {
975 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000976 Left->MatchingParen = CurrentToken;
977 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000978 next();
979 return true;
980 }
981 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
982 return false;
983 if (!consumeToken())
984 return false;
985 }
Daniel Jasper83a54d22013-01-10 09:26:47 +0000986 return true;
987 }
988
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000989 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000990 while (CurrentToken != NULL) {
991 if (CurrentToken->is(tok::colon)) {
992 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000993 next();
994 return true;
995 }
Daniel Jasperc0880a92013-01-04 18:52:56 +0000996 if (!consumeToken())
997 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000998 }
999 return false;
1000 }
1001
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001002 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001003 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1004 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001005 next();
1006 if (!parseAngle())
1007 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001008 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001009 return true;
1010 }
1011 return false;
1012 }
1013
Daniel Jasperc0880a92013-01-04 18:52:56 +00001014 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001015 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001017 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001018 case tok::plus:
1019 case tok::minus:
1020 // At the start of the line, +/- specific ObjectiveC method
1021 // declarations.
1022 if (Tok->Parent == NULL)
1023 Tok->Type = TT_ObjCMethodSpecifier;
1024 break;
Nico Webera7252d82013-01-12 06:18:40 +00001025 case tok::colon:
1026 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001027 if (Tok->Parent->is(tok::r_paren))
1028 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001029 if (ColonIsObjCMethodExpr)
1030 Tok->Type = TT_ObjCMethodExpr;
1031 break;
Nico Weber80a82762013-01-17 17:17:19 +00001032 case tok::kw_if:
1033 case tok::kw_while:
1034 if (CurrentToken->is(tok::l_paren)) {
1035 next();
1036 if (!parseParens(/*LookForDecls=*/true))
1037 return false;
1038 }
1039 break;
Nico Webera5510af2013-01-18 05:50:57 +00001040 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001041 if (!parseParens())
1042 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001043 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001044 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001045 if (!parseSquare())
1046 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001047 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001048 case tok::l_brace:
1049 if (!parseBrace())
1050 return false;
1051 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001052 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001053 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001054 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001055 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001056 Tok->Type = TT_BinaryOperator;
1057 CurrentToken = Tok;
1058 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001059 }
1060 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001061 case tok::r_paren:
1062 case tok::r_square:
1063 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001064 case tok::r_brace:
1065 // Lines can start with '}'.
1066 if (Tok->Parent != NULL)
1067 return false;
1068 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001069 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001070 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001071 break;
1072 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001073 if (CurrentToken->is(tok::l_paren)) {
1074 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001075 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001076 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1077 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001078 next();
1079 }
1080 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001081 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1082 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001083 next();
1084 }
1085 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001086 break;
1087 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001088 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001089 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001090 case tok::kw_template:
1091 parseTemplateDeclaration();
1092 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 default:
1094 break;
1095 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001096 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001097 }
1098
Daniel Jasper050948a52012-12-21 17:58:39 +00001099 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001100 next();
1101 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1102 next();
1103 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001104 if (CurrentToken->isNot(tok::comment) ||
1105 !CurrentToken->Children.empty())
1106 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001107 next();
1108 }
1109 } else {
1110 while (CurrentToken != NULL) {
1111 next();
1112 }
1113 }
1114 }
1115
1116 void parseWarningOrError() {
1117 next();
1118 // We still want to format the whitespace left of the first token of the
1119 // warning or error.
1120 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001121 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001122 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001123 next();
1124 }
1125 }
1126
1127 void parsePreprocessorDirective() {
1128 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001129 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001130 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001131 // Hashes in the middle of a line can lead to any strange token
1132 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001133 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001134 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 switch (
1136 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001137 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001138 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001139 parseIncludeDirective();
1140 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001141 case tok::pp_error:
1142 case tok::pp_warning:
1143 parseWarningOrError();
1144 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001145 default:
1146 break;
1147 }
1148 }
1149
Daniel Jasperda16db32013-01-07 10:48:50 +00001150 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001151 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001152 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001153 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001154 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001155 while (CurrentToken != NULL) {
1156 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001157 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001158 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001159 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001160 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001161 if (KeywordVirtualFound)
1162 return LT_VirtualFunctionDecl;
1163 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001164 }
1165
1166 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001167 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1168 CurrentToken = &CurrentToken->Children[0];
1169 else
1170 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001171 }
1172
1173 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001174 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001175 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001176 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001177 };
1178
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001179 void calculateExtraInformation(AnnotatedToken &Current) {
1180 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1181
Manuel Klimek52b15152013-01-09 15:25:02 +00001182 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001183 Current.MustBreakBefore = true;
1184 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001185 if (Current.Type == TT_LineComment) {
1186 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001187 } else if ((Current.Parent->is(tok::comment) &&
1188 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001189 (Current.is(tok::string_literal) &&
1190 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001191 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001192 } else {
1193 Current.MustBreakBefore = false;
1194 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001195 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001196 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001197 if (Current.MustBreakBefore)
1198 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1199 else
1200 Current.TotalLength = Current.Parent->TotalLength +
1201 Current.FormatTok.TokenLength +
1202 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001203 if (!Current.Children.empty())
1204 calculateExtraInformation(Current.Children[0]);
1205 }
1206
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001207 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001208 AnnotatingParser Parser(Line.First);
1209 Line.Type = Parser.parseLine();
1210 if (Line.Type == LT_Invalid)
1211 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001212
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001213 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001214
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001215 if (Line.First.Type == TT_ObjCMethodSpecifier)
1216 Line.Type = LT_ObjCMethodDecl;
1217 else if (Line.First.Type == TT_ObjCDecl)
1218 Line.Type = LT_ObjCDecl;
1219 else if (Line.First.Type == TT_ObjCProperty)
1220 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001221
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001222 Line.First.SpaceRequiredBefore = true;
1223 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1224 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001225
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001226 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001227 if (!Line.First.Children.empty())
1228 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001229 }
1230
1231private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001232 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1233 if (getPrecedence(Current) == prec::Assignment ||
1234 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1235 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001236
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001237 if (Current.Type == TT_Unknown) {
1238 if (Current.is(tok::star) || Current.is(tok::amp)) {
1239 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001240 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1241 Current.is(tok::caret)) {
1242 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001243 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1244 Current.Type = determineIncrementUsage(Current);
1245 } else if (Current.is(tok::exclaim)) {
1246 Current.Type = TT_UnaryOperator;
1247 } else if (isBinaryOperator(Current)) {
1248 Current.Type = TT_BinaryOperator;
1249 } else if (Current.is(tok::comment)) {
1250 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1251 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001252 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001253 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001255 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001256 } else if (Current.is(tok::r_paren) &&
1257 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001258 Current.Parent->Type == TT_TemplateCloser) &&
1259 (Current.Children.empty() ||
1260 (Current.Children[0].isNot(tok::equal) &&
1261 Current.Children[0].isNot(tok::semi) &&
1262 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001263 // FIXME: We need to get smarter and understand more cases of casts.
1264 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001265 } else if (Current.is(tok::at) && Current.Children.size()) {
1266 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1267 case tok::objc_interface:
1268 case tok::objc_implementation:
1269 case tok::objc_protocol:
1270 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001271 break;
1272 case tok::objc_property:
1273 Current.Type = TT_ObjCProperty;
1274 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001275 default:
1276 break;
1277 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001278 }
1279 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001280
1281 if (!Current.Children.empty())
1282 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001283 }
1284
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001285 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001286 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001287 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001288 }
1289
Daniel Jasper71945272013-01-15 14:27:39 +00001290 /// \brief Returns the previous token ignoring comments.
1291 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1292 const AnnotatedToken *PrevToken = Tok.Parent;
1293 while (PrevToken != NULL && PrevToken->is(tok::comment))
1294 PrevToken = PrevToken->Parent;
1295 return PrevToken;
1296 }
1297
1298 /// \brief Returns the next token ignoring comments.
1299 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1300 if (Tok.Children.empty())
1301 return NULL;
1302 const AnnotatedToken *NextToken = &Tok.Children[0];
1303 while (NextToken->is(tok::comment)) {
1304 if (NextToken->Children.empty())
1305 return NULL;
1306 NextToken = &NextToken->Children[0];
1307 }
1308 return NextToken;
1309 }
1310
1311 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001312 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001313 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1314 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001315 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001316
1317 const AnnotatedToken *NextToken = getNextToken(Tok);
1318 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001319 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001320
Daniel Jasper71945272013-01-15 14:27:39 +00001321 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1322 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1323 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1324 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001325 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001326 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001327
Daniel Jasper71945272013-01-15 14:27:39 +00001328 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1329 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1330 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1331 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1332 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1333 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1334 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001335 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001336
Daniel Jasper71945272013-01-15 14:27:39 +00001337 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1338 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001339 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001340
Daniel Jasper426702d2012-12-05 07:51:39 +00001341 // It is very unlikely that we are going to find a pointer or reference type
1342 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001343 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001344 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001345
Daniel Jasperda16db32013-01-07 10:48:50 +00001346 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001347 }
1348
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001349 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001350 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1351 if (PrevToken == NULL)
1352 return TT_UnaryOperator;
1353
Daniel Jasper8dd40472012-12-21 09:41:31 +00001354 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001355 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1356 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1357 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1358 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1359 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001360 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001361
1362 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001363 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001364 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001365
1366 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001367 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001368 }
1369
1370 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001371 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001372 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1373 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001374 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001375 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1376 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001377 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001378
Daniel Jasperda16db32013-01-07 10:48:50 +00001379 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001380 }
1381
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001382 bool spaceRequiredBetween(const AnnotatedToken &Left,
1383 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001384 if (Right.is(tok::hashhash))
1385 return Left.is(tok::hash);
1386 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1387 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001388 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1389 return false;
Nico Webera6087752013-01-10 20:12:55 +00001390 if (Right.is(tok::less) &&
1391 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001392 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001393 return true;
1394 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1395 return false;
1396 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1397 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001398 if (Left.is(tok::at) &&
1399 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1400 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001401 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1402 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001403 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001404 if (Left.is(tok::coloncolon))
1405 return false;
1406 if (Right.is(tok::coloncolon))
1407 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001408 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1409 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001410 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001411 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001412 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1413 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001414 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001415 return Right.FormatTok.Tok.isLiteral() ||
1416 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001417 if (Right.is(tok::star) && Left.is(tok::l_paren))
1418 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001419 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1420 return false;
1421 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001422 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001423 if (Left.is(tok::period) || Right.is(tok::period))
1424 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001425 if (Left.is(tok::colon))
1426 return Left.Type != TT_ObjCMethodExpr;
1427 if (Right.is(tok::colon))
1428 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001429 if (Left.is(tok::l_paren))
1430 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001431 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001432 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001433 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001434 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001435 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1436 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001437 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001438 if (Left.is(tok::at) &&
1439 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001440 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001441 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1442 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001443 return true;
1444 }
1445
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001446 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001447 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001448 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1449 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001450 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001451 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001452 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001453 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001454 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001455 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001456 // Don't space between ')' and <id>
1457 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001458 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001459 // Don't space between ':' and '('
1460 return false;
1461 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001462 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001463 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1464 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001465
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001466 if (Tok.Parent->is(tok::comma))
1467 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001468 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001469 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001470 if (Tok.Type == TT_OverloadedOperator)
1471 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001472 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001473 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001474 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001475 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001476 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001477 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001478 if (Tok.Parent->Type == TT_UnaryOperator ||
1479 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001480 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001481 if (Tok.Type == TT_UnaryOperator)
1482 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001483 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1484 (Tok.Parent->isNot(tok::colon) ||
1485 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001486 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1487 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001488 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1489 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001490 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001491 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001492 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001493 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001494 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001495 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001496 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001497 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001498 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001499 }
1500
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001501 bool canBreakBefore(const AnnotatedToken &Right) {
1502 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001503 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001504 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1505 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001506 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001507 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1508 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001509 // Don't break this identifier as ':' or identifier
1510 // before it will break.
1511 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001512 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1513 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001514 // Don't break at ':' if identifier before it can beak.
1515 return false;
1516 }
Nico Webera7252d82013-01-12 06:18:40 +00001517 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1518 return false;
1519 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1520 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001521 if (isObjCSelectorName(Right))
1522 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001523 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001524 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001525 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001526 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001527 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001528 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001529 return false;
1530
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001531 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001532 // We rely on MustBreakBefore being set correctly here as we should not
1533 // change the "binding" behavior of a comment.
1534 return false;
1535
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001536 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1537 // unless it is follow by ';', '{' or '='.
1538 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1539 Left.Parent->is(tok::r_paren))
1540 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1541 Right.isNot(tok::equal);
1542
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001543 // We only break before r_brace if there was a corresponding break before
1544 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1545 if (Right.is(tok::r_brace))
1546 return false;
1547
Daniel Jasper71945272013-01-15 14:27:39 +00001548 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001549 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001550 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1551 Left.is(tok::comma) || Right.is(tok::lessless) ||
1552 Right.is(tok::arrow) || Right.is(tok::period) ||
1553 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001554 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1555 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1556 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001557 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001558 }
1559
Daniel Jasperf7935112012-12-03 18:12:45 +00001560 FormatStyle Style;
1561 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001562 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001563 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001564};
1565
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001566class LexerBasedFormatTokenSource : public FormatTokenSource {
1567public:
1568 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001569 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001570 IdentTable(Lex.getLangOpts()) {
1571 Lex.SetKeepWhitespaceMode(true);
1572 }
1573
1574 virtual FormatToken getNextToken() {
1575 if (GreaterStashed) {
1576 FormatTok.NewlinesBefore = 0;
1577 FormatTok.WhiteSpaceStart =
1578 FormatTok.Tok.getLocation().getLocWithOffset(1);
1579 FormatTok.WhiteSpaceLength = 0;
1580 GreaterStashed = false;
1581 return FormatTok;
1582 }
1583
1584 FormatTok = FormatToken();
1585 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001586 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001587 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001588 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1589 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001590
1591 // Consume and record whitespace until we find a significant token.
1592 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001593 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001594 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1595 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001596 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1597
1598 if (FormatTok.Tok.is(tok::eof))
1599 return FormatTok;
1600 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001601 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001602 }
Manuel Klimekef920692013-01-07 07:56:50 +00001603
1604 // Now FormatTok is the next non-whitespace token.
1605 FormatTok.TokenLength = Text.size();
1606
Manuel Klimek1abf7892013-01-04 23:34:14 +00001607 // In case the token starts with escaped newlines, we want to
1608 // take them into account as whitespace - this pattern is quite frequent
1609 // in macro definitions.
1610 // FIXME: What do we want to do with other escaped spaces, and escaped
1611 // spaces or newlines in the middle of tokens?
1612 // FIXME: Add a more explicit test.
1613 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001614 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001615 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001616 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001617 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001618 }
1619
1620 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001621 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001622 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001623 FormatTok.Tok.setKind(Info.getTokenID());
1624 }
1625
1626 if (FormatTok.Tok.is(tok::greatergreater)) {
1627 FormatTok.Tok.setKind(tok::greater);
1628 GreaterStashed = true;
1629 }
1630
1631 return FormatTok;
1632 }
1633
1634private:
1635 FormatToken FormatTok;
1636 bool GreaterStashed;
1637 Lexer &Lex;
1638 SourceManager &SourceMgr;
1639 IdentifierTable IdentTable;
1640
1641 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001642 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001643 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1644 Tok.getLength());
1645 }
1646};
1647
Daniel Jasperf7935112012-12-03 18:12:45 +00001648class Formatter : public UnwrappedLineConsumer {
1649public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001650 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1651 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001652 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001653 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001654 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001655
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001656 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001657
Daniel Jasperf7935112012-12-03 18:12:45 +00001658 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001659 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001660 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001661 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001662 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001663 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1664 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1665 Annotator.annotate();
1666 }
1667 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1668 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001669 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001670 const AnnotatedLine &TheLine = *I;
1671 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1672 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1673 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001674 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001675 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001676 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001677 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001678 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001679 PreviousEndOfLineColumn = Formatter.format();
1680 } else {
1681 // If we did not reformat this unwrapped line, the column at the end of
1682 // the last token is unchanged - thus, we can calculate the end of the
1683 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001684 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001685 SourceMgr.getSpellingColumnNumber(
1686 TheLine.Last->FormatTok.Tok.getLocation()) +
1687 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1688 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001689 1;
1690 }
1691 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001692 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001693 }
1694
1695private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001696 /// \brief Tries to merge lines into one.
1697 ///
1698 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1699 /// if possible; note that \c I will be incremented when lines are merged.
1700 ///
1701 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001702 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001703 std::vector<AnnotatedLine>::iterator &I,
1704 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001705 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1706
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001707 // We can never merge stuff if there are trailing line comments.
1708 if (I->Last->Type == TT_LineComment)
1709 return;
1710
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001711 // Check whether the UnwrappedLine can be put onto a single line. If
1712 // so, this is bound to be the optimal solution (by definition) and we
1713 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001714 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001715 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001716 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001717
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001718 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001719 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001720
Daniel Jasper25837aa2013-01-14 14:14:23 +00001721 if (I->Last->is(tok::l_brace)) {
1722 tryMergeSimpleBlock(I, E, Limit);
1723 } else if (I->First.is(tok::kw_if)) {
1724 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001725 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1726 I->First.FormatTok.IsFirst)) {
1727 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001728 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001729 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001730 }
1731
Daniel Jasper39825ea2013-01-14 15:40:57 +00001732 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1733 std::vector<AnnotatedLine>::iterator E,
1734 unsigned Limit) {
1735 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001736 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1737 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001738 if (I + 2 != E && (I + 2)->InPPDirective &&
1739 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1740 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001741 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001742 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001743 join(Line, *(++I));
1744 }
1745
Daniel Jasper25837aa2013-01-14 14:14:23 +00001746 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1747 std::vector<AnnotatedLine>::iterator E,
1748 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001749 if (!Style.AllowShortIfStatementsOnASingleLine)
1750 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001751 if ((I + 1)->InPPDirective != I->InPPDirective ||
1752 ((I + 1)->InPPDirective &&
1753 (I + 1)->First.FormatTok.HasUnescapedNewline))
1754 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001755 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001756 if (Line.Last->isNot(tok::r_paren))
1757 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001758 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001759 return;
1760 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1761 return;
1762 // Only inline simple if's (no nested if or else).
1763 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1764 return;
1765 join(Line, *(++I));
1766 }
1767
1768 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1769 std::vector<AnnotatedLine>::iterator E,
1770 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001771 // First, check that the current line allows merging. This is the case if
1772 // we're not in a control flow statement and the last token is an opening
1773 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001774 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001775 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001776 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1777 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1778 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1779 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001780 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001781 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1782 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001783 if (!AllowedTokens)
1784 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001785
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001786 AnnotatedToken *Tok = &(I + 1)->First;
1787 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1788 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1789 Tok->SpaceRequiredBefore = false;
1790 join(Line, *(I + 1));
1791 I += 1;
1792 } else {
1793 // Check that we still have three lines and they fit into the limit.
1794 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1795 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001796 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001797
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001798 // Second, check that the next line does not contain any braces - if it
1799 // does, readability declines when putting it into a single line.
1800 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1801 return;
1802 do {
1803 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1804 return;
1805 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1806 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001807
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001808 // Last, check that the third line contains a single closing brace.
1809 Tok = &(I + 2)->First;
1810 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1811 Tok->MustBreakBefore)
1812 return;
1813
1814 join(Line, *(I + 1));
1815 join(Line, *(I + 2));
1816 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001817 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001818 }
1819
1820 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1821 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001822 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1823 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001824 }
1825
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001826 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1827 A.Last->Children.push_back(B.First);
1828 while (!A.Last->Children.empty()) {
1829 A.Last->Children[0].Parent = A.Last;
1830 A.Last = &A.Last->Children[0];
1831 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001832 }
1833
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001834 bool touchesRanges(const AnnotatedLine &TheLine) {
1835 const FormatToken *First = &TheLine.First.FormatTok;
1836 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001837 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001838 First->Tok.getLocation(),
1839 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001840 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001841 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1842 Ranges[i].getBegin()) &&
1843 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1844 LineRange.getBegin()))
1845 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001846 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001847 return false;
1848 }
1849
1850 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001851 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001852 }
1853
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001854 /// \brief Add a new line and the required indent before the first Token
1855 /// of the \c UnwrappedLine if there was no structural parsing error.
1856 /// Returns the indent level of the \c UnwrappedLine.
1857 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1858 bool InPPDirective,
1859 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001860 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001861 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1862 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1863
1864 unsigned Newlines = std::min(Tok.NewlinesBefore,
1865 Style.MaxEmptyLinesToKeep + 1);
1866 if (Newlines == 0 && !Tok.IsFirst)
1867 Newlines = 1;
1868 unsigned Indent = Level * 2;
1869
1870 bool IsAccessModifier = false;
1871 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1872 RootToken.is(tok::kw_private))
1873 IsAccessModifier = true;
1874 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1875 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1876 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1877 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1878 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1879 IsAccessModifier = true;
1880
1881 if (IsAccessModifier &&
1882 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1883 Indent += Style.AccessModifierOffset;
1884 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001885 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001886 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001887 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1888 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001889 }
1890 return Indent;
1891 }
1892
Alexander Kornienko116ba682013-01-14 11:34:14 +00001893 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001894 FormatStyle Style;
1895 Lexer &Lex;
1896 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001897 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001898 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001899 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001900 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001901};
1902
1903tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1904 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001905 std::vector<CharSourceRange> Ranges,
1906 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001907 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001908 OwningPtr<DiagnosticConsumer> DiagPrinter;
1909 if (DiagClient == 0) {
1910 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1911 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1912 DiagClient = DiagPrinter.get();
1913 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001914 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001915 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001916 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001917 Diagnostics.setSourceManager(&SourceMgr);
1918 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001919 return formatter.format();
1920}
1921
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001922LangOptions getFormattingLangOpts() {
1923 LangOptions LangOpts;
1924 LangOpts.CPlusPlus = 1;
1925 LangOpts.CPlusPlus11 = 1;
1926 LangOpts.Bool = 1;
1927 LangOpts.ObjC1 = 1;
1928 LangOpts.ObjC2 = 1;
1929 return LangOpts;
1930}
1931
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001932} // namespace format
1933} // namespace clang