blob: e9ff3c9b129da77d65708413e7d6c04b0bda5901 [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) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000205 // 2+ newlines mean an empty line separating logic scopes.
206 if (NewLines >= 2)
207 alignComments();
208
209 // Align line comments if they are trailing or if they continue other
210 // trailing comments.
211 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212 (Tok.Parent != NULL || !Comments.empty())) {
213 if (Style.ColumnLimit >=
214 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
215 Comments.push_back(StoredComment());
216 Comments.back().Tok = Tok.FormatTok;
217 Comments.back().Spaces = Spaces;
218 Comments.back().NewLines = NewLines;
219 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
220 Comments.back().MaxColumn = Style.ColumnLimit -
221 Spaces - Tok.FormatTok.TokenLength;
222 return;
223 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000224 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000225
226 // If this line does not have a trailing comment, align the stored comments.
227 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
228 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000229 storeReplacement(Tok.FormatTok,
230 std::string(NewLines, '\n') + std::string(Spaces, ' '));
231 }
232
233 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
234 /// backslashes to escape newlines inside a preprocessor directive.
235 ///
236 /// This function and \c replaceWhitespace have the same behavior if
237 /// \c Newlines == 0.
238 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
239 unsigned Spaces, unsigned WhitespaceStartColumn,
240 const FormatStyle &Style) {
241 std::string NewLineText;
242 if (NewLines > 0) {
243 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
244 WhitespaceStartColumn);
245 for (unsigned i = 0; i < NewLines; ++i) {
246 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
247 NewLineText += "\\\n";
248 Offset = 0;
249 }
250 }
251 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
252 }
253
254 /// \brief Returns all the \c Replacements created during formatting.
255 const tooling::Replacements &generateReplacements() {
256 alignComments();
257 return Replaces;
258 }
259
260private:
261 /// \brief Structure to store a comment for later layout and alignment.
262 struct StoredComment {
263 FormatToken Tok;
264 unsigned MinColumn;
265 unsigned MaxColumn;
266 unsigned NewLines;
267 unsigned Spaces;
268 };
269 SmallVector<StoredComment, 16> Comments;
270 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
271
272 /// \brief Try to align all stashed comments.
273 void alignComments() {
274 unsigned MinColumn = 0;
275 unsigned MaxColumn = UINT_MAX;
276 comment_iterator Start = Comments.begin();
277 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
278 ++I) {
279 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
280 alignComments(Start, I, MinColumn);
281 MinColumn = I->MinColumn;
282 MaxColumn = I->MaxColumn;
283 Start = I;
284 } else {
285 MinColumn = std::max(MinColumn, I->MinColumn);
286 MaxColumn = std::min(MaxColumn, I->MaxColumn);
287 }
288 }
289 alignComments(Start, Comments.end(), MinColumn);
290 Comments.clear();
291 }
292
293 /// \brief Put all the comments between \p I and \p E into \p Column.
294 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
295 while (I != E) {
296 unsigned Spaces = I->Spaces + Column - I->MinColumn;
297 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
298 std::string(Spaces, ' '));
299 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000300 }
301 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000302
303 /// \brief Stores \p Text as the replacement for the whitespace in front of
304 /// \p Tok.
305 void storeReplacement(const FormatToken &Tok, const std::string Text) {
306 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
307 Tok.WhiteSpaceLength, Text));
308 }
309
310 SourceManager &SourceMgr;
311 tooling::Replacements Replaces;
312};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000313
Nico Weberc9d73612013-01-12 22:48:47 +0000314/// \brief Returns if a token is an Objective-C selector name.
315///
Nico Weber92c05392013-01-12 22:51:13 +0000316/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000317static bool isObjCSelectorName(const AnnotatedToken &Tok) {
318 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
319 Tok.Children[0].is(tok::colon) &&
320 Tok.Children[0].Type == TT_ObjCMethodExpr;
321}
322
Daniel Jasperf7935112012-12-03 18:12:45 +0000323class UnwrappedLineFormatter {
324public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000325 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000326 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000327 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000328 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000329 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000330 FirstIndent(FirstIndent), RootToken(RootToken),
331 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000332 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000333 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000334 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000335 }
336
Manuel Klimek1abf7892013-01-04 23:34:14 +0000337 /// \brief Formats an \c UnwrappedLine.
338 ///
339 /// \returns The column after the last token in the last line of the
340 /// \c UnwrappedLine.
341 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000342 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000343 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000344 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000345 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000346 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000347 State.ForLoopVariablePos = 0;
348 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000349 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000350
Manuel Klimek24998102013-01-16 14:55:28 +0000351 DEBUG({
352 DebugTokenState(*State.NextToken);
353 });
354
Daniel Jaspere9de2602012-12-06 09:56:08 +0000355 // The first token has already been indented and thus consumed.
356 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000357
358 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000359 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000360 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
361 // Calculating the column is important for aligning trailing comments.
362 // FIXME: This does not seem to happen in conjunction with escaped
363 // newlines. If it does, fix!
364 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
365 State.NextToken->FormatTok.TokenLength;
366 State.NextToken = State.NextToken->Children.empty() ? NULL :
367 &State.NextToken->Children[0];
368 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000369 addTokenToState(false, false, State);
370 } else {
371 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
372 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000373 DEBUG({
374 if (Break < NoBreak)
375 llvm::errs() << "\n";
376 else
377 llvm::errs() << " ";
378 llvm::errs() << "<";
379 DebugPenalty(Break, Break < NoBreak);
380 llvm::errs() << "/";
381 DebugPenalty(NoBreak, !(Break < NoBreak));
382 llvm::errs() << "> ";
383 DebugTokenState(*State.NextToken);
384 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000385 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000386 if (State.NextToken != NULL &&
387 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
388 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000389 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000390 State.Stack.back().BreakAfterComma = true;
391 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000392 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000393 }
Manuel Klimek24998102013-01-16 14:55:28 +0000394 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000395 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000396 }
397
398private:
Manuel Klimek24998102013-01-16 14:55:28 +0000399 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
400 const Token &Tok = AnnotatedTok.FormatTok.Tok;
401 llvm::errs()
402 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
403 Tok.getLength());
404 llvm::errs();
405 }
406
407 void DebugPenalty(unsigned Penalty, bool Winner) {
408 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
409 if (Penalty == UINT_MAX)
410 llvm::errs() << "MAX";
411 else
412 llvm::errs() << Penalty;
413 llvm::errs().resetColor();
414 }
415
Daniel Jasper337816e2013-01-11 10:22:12 +0000416 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000417 ParenState(unsigned Indent, unsigned LastSpace)
418 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000419 BreakBeforeClosingBrace(false), BreakAfterComma(false),
420 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000421
Daniel Jasperf7935112012-12-03 18:12:45 +0000422 /// \brief The position to which a specific parenthesis level needs to be
423 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jaspere9de2602012-12-06 09:56:08 +0000426 /// \brief The position of the last space on each level.
427 ///
428 /// Used e.g. to break like:
429 /// functionCall(Parameter, otherCall(
430 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000432
Daniel Jaspere9de2602012-12-06 09:56:08 +0000433 /// \brief The position the first "<<" operator encountered on each level.
434 ///
435 /// Used to align "<<" operators. 0 if no such operator has been encountered
436 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000438
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000439 /// \brief Whether a newline needs to be inserted before the block's closing
440 /// brace.
441 ///
442 /// We only want to insert a newline before the closing brace if there also
443 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000444 bool BreakBeforeClosingBrace;
445
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000446 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000447 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000448
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 bool operator<(const ParenState &Other) const {
450 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000451 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000452 if (LastSpace != Other.LastSpace)
453 return LastSpace < Other.LastSpace;
454 if (FirstLessLess != Other.FirstLessLess)
455 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000456 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
457 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000458 if (BreakAfterComma != Other.BreakAfterComma)
459 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000460 if (HasMultiParameterLine != Other.HasMultiParameterLine)
461 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000462 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000463 }
464 };
465
466 /// \brief The current state when indenting a unwrapped line.
467 ///
468 /// As the indenting tries different combinations this is copied by value.
469 struct LineState {
470 /// \brief The number of used columns in the current line.
471 unsigned Column;
472
473 /// \brief The token that needs to be next formatted.
474 const AnnotatedToken *NextToken;
475
476 /// \brief The parenthesis level of the first token on the current line.
477 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000478
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000479 /// \brief The column of the first variable in a for-loop declaration.
480 ///
481 /// Used to align the second variable if necessary.
482 unsigned ForLoopVariablePos;
483
484 /// \brief \c true if this line contains a continued for-loop section.
485 bool LineContainsContinuedForLoopSection;
486
Daniel Jasper337816e2013-01-11 10:22:12 +0000487 /// \brief A stack keeping track of properties applying to parenthesis
488 /// levels.
489 std::vector<ParenState> Stack;
490
491 /// \brief Comparison operator to be able to used \c LineState in \c map.
492 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000493 if (Other.NextToken != NextToken)
494 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000495 if (Other.Column != Column)
496 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000497 if (Other.StartOfLineLevel != StartOfLineLevel)
498 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 if (Other.ForLoopVariablePos != ForLoopVariablePos)
500 return Other.ForLoopVariablePos < ForLoopVariablePos;
501 if (Other.LineContainsContinuedForLoopSection !=
502 LineContainsContinuedForLoopSection)
503 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000504 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000505 }
506 };
507
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000508 /// \brief Appends the next token to \p State and updates information
509 /// necessary for indentation.
510 ///
511 /// Puts the token on the current line if \p Newline is \c true and adds a
512 /// line break and necessary indentation otherwise.
513 ///
514 /// If \p DryRun is \c false, also creates and stores the required
515 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000516 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000517 const AnnotatedToken &Current = *State.NextToken;
518 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 assert(State.Stack.size());
520 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000521
522 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000523 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000524 if (Current.is(tok::r_brace)) {
525 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000526 } else if (Current.is(tok::string_literal) &&
527 Previous.is(tok::string_literal)) {
528 State.Column = State.Column - Previous.FormatTok.TokenLength;
529 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 State.Stack[ParenLevel].FirstLessLess != 0) {
531 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000532 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
534 Current.is(tok::period) || Previous.is(tok::question) ||
535 Previous.Type == TT_ConditionalExpr)) {
536 // Indent and extra 4 spaces after if we know the current expression is
537 // continued. Don't do that on the top level, as we already indent 4
538 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000540 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000541 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000542 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000544 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000546 }
547
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 // A line starting with a closing brace is assumed to be correct for the
549 // same level as before the opening brace.
550 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000551
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000552 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000553 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000555 if (!DryRun) {
556 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000557 Whitespaces.replaceWhitespace(Current, 1, State.Column,
558 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000559 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000560 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
561 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000562 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000563
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000565 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000566 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000567 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000568 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
569 State.ForLoopVariablePos = State.Column -
570 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000571
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
573 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000574 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000575
Daniel Jasperf7935112012-12-03 18:12:45 +0000576 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000577 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000578
Daniel Jasperbcab4302013-01-09 10:40:23 +0000579 // FIXME: Do we need to do this for assignments nested in other
580 // expressions?
581 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000582 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000583 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000584 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000585 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000586 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000587 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000588 if (Current.getPreviousNoneComment()->is(tok::comma) &&
589 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000590 State.Stack[ParenLevel].HasMultiParameterLine = true;
591
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000592
Daniel Jasper206df732013-01-07 13:08:40 +0000593 // Top-level spaces that are not part of assignments are exempt as that
594 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000595 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000596 if (Spaces > 0 &&
597 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000598 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000600
601 // If we break after an {, we should also break before the corresponding }.
602 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000603 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000604
605 // If we are breaking after '(', '{', '<' or ',', we need to break after
606 // future commas as well to avoid bin packing.
607 if (!Style.BinPackParameters && Newline &&
608 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
609 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
610 State.Stack.back().BreakAfterComma = true;
611
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000612 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000614
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000615 /// \brief Mark the next token as consumed in \p State and modify its stacks
616 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000617 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000618 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000619 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000620
Daniel Jasper337816e2013-01-11 10:22:12 +0000621 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
622 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000623
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000624 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000625 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000626 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
627 Current.is(tok::l_brace) ||
628 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000629 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000630 if (Current.is(tok::l_brace)) {
631 // FIXME: This does not work with nested static initializers.
632 // Implement a better handling for static initializers and similar
633 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000634 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000635 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000636 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000637 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000638 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000639 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000640
641 // If the entire set of parameters will not fit on the current line, we
642 // will need to break after commas on this level to avoid bin-packing.
643 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
644 !Current.Children.empty()) {
645 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
646 Current.MatchingParen->TotalLength -
647 Current.Children[0].TotalLength) {
648 State.Stack.back().BreakAfterComma = true;
649 }
650 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000651 }
652
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000653 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000655 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
656 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
657 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000658 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000660
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000661 if (State.NextToken->Children.empty())
662 State.NextToken = NULL;
663 else
664 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000665
666 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000667 }
668
Nico Weber49cbc2c2013-01-07 15:15:29 +0000669 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 unsigned splitPenalty(const AnnotatedToken &Tok) {
671 const AnnotatedToken &Left = Tok;
672 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000673
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000674 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
675 return 50;
676 if (Left.is(tok::equal) && Right.is(tok::l_brace))
677 return 150;
678
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000679 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 if (RootToken.is(tok::kw_for) &&
681 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000682 return 20;
683
Daniel Jasper04468962013-01-18 10:56:38 +0000684 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000685 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000686
687 // In Objective-C method expressions, prefer breaking before "param:" over
688 // breaking after it.
689 if (isObjCSelectorName(Right))
690 return 0;
691 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
692 return 20;
693
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000694 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000695 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000696
Daniel Jasper399d24b2013-01-09 07:06:56 +0000697 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
698 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000699 prec::Level Level = getPrecedence(Left);
700
701 // Breaking after an assignment leads to a bad result as the two sides of
702 // the assignment are visually very close together.
703 if (Level == prec::Assignment)
704 return 50;
705
Daniel Jasperde5c2072012-12-24 00:13:23 +0000706 if (Level != prec::Unknown)
707 return Level;
708
Daniel Jasper04468962013-01-18 10:56:38 +0000709 if (Right.is(tok::arrow) || Right.is(tok::period)) {
710 if (Left.is(tok::r_paren))
711 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000712 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000713 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000714
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 return 3;
716 }
717
Daniel Jasper2df93312013-01-09 10:16:05 +0000718 unsigned getColumnLimit() {
719 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
720 }
721
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 /// \brief Calculate the number of lines needed to format the remaining part
723 /// of the unwrapped line.
724 ///
725 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000726 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000727 /// added after the previous token.
728 ///
729 /// \param StopAt is used for optimization. If we can determine that we'll
730 /// definitely need at least \p StopAt additional lines, we already know of a
731 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000732 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000734 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 return 0;
736
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000737 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000739 if (NewLine && !State.NextToken->CanBreakBefore &&
740 !(State.NextToken->is(tok::r_brace) &&
741 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000743 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000744 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000745 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000746 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000747 State.LineContainsContinuedForLoopSection)
748 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000749 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000750 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000751 State.Stack.back().BreakAfterComma)
752 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000753 // Trying to insert a parameter on a new line if there are already more than
754 // one parameter on the current line is bin packing.
755 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
756 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
757 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000758 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
759 (State.NextToken->Parent->ClosesTemplateDeclaration &&
760 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000761 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000762
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000763 unsigned CurrentPenalty = 0;
764 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000765 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000766 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000767 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000768 if (State.Stack.size() < State.StartOfLineLevel &&
769 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000770 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000771 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000772 }
773
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000774 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000775
Daniel Jasper2df93312013-01-09 10:16:05 +0000776 // Exceeding column limit is bad, assign penalty.
777 if (State.Column > getColumnLimit()) {
778 unsigned ExcessCharacters = State.Column - getColumnLimit();
779 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
780 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000781
Daniel Jasperf7935112012-12-03 18:12:45 +0000782 if (StopAt <= CurrentPenalty)
783 return UINT_MAX;
784 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000786 if (I != Memory.end()) {
787 // If this state has already been examined, we can safely return the
788 // previous result if we
789 // - have not hit the optimatization (and thus returned UINT_MAX) OR
790 // - are now computing for a smaller or equal StopAt.
791 unsigned SavedResult = I->second.first;
792 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000793 if (SavedResult != UINT_MAX)
794 return SavedResult + CurrentPenalty;
795 else if (StopAt <= SavedStopAt)
796 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000797 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000798
799 unsigned NoBreak = calcPenalty(State, false, StopAt);
800 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
801 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000802
803 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
804 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000805 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000806
807 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 }
809
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 FormatStyle Style;
811 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000812 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000813 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000814 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000815 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000816
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000817 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000818 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000819 StateMap Memory;
820
Daniel Jasperf7935112012-12-03 18:12:45 +0000821 OptimizationParameters Parameters;
822};
823
824/// \brief Determines extra information about the tokens comprising an
825/// \c UnwrappedLine.
826class TokenAnnotator {
827public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000828 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
829 AnnotatedLine &Line)
830 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000831
832 /// \brief A parser that gathers additional information about tokens.
833 ///
834 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
835 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
836 /// into template parameter lists.
837 class AnnotatingParser {
838 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000840 : CurrentToken(&RootToken), KeywordVirtualFound(false),
841 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000842
Nico Weber250fe712013-01-18 02:43:57 +0000843 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
844 struct ObjCSelectorRAII {
845 AnnotatingParser &P;
846 bool ColonWasObjCMethodExpr;
847
848 ObjCSelectorRAII(AnnotatingParser &P)
849 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
850
851 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
852
853 void markStart(AnnotatedToken &Left) {
854 P.ColonIsObjCMethodExpr = true;
855 Left.Type = TT_ObjCMethodExpr;
856 }
857
858 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
859 };
860
861
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000862 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000863 if (CurrentToken == NULL)
864 return false;
865 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000866 while (CurrentToken != NULL) {
867 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000868 Left->MatchingParen = CurrentToken;
869 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000871 next();
872 return true;
873 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
875 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000876 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000877 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
878 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000879 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000880 if (!consumeToken())
881 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000882 }
883 return false;
884 }
885
Nico Weber80a82762013-01-17 17:17:19 +0000886 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000887 if (CurrentToken == NULL)
888 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000889 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000890 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000891 if (CurrentToken->is(tok::caret)) {
892 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000893 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000894 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
895 // @selector( starts a selector.
896 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
897 MaybeSel->Parent->is(tok::at)) {
898 StartsObjCMethodExpr = true;
899 }
900 }
901
902 ObjCSelectorRAII objCSelector(*this);
903 if (StartsObjCMethodExpr)
904 objCSelector.markStart(*Left);
905
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000906 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000907 // LookForDecls is set when "if (" has been seen. Check for
908 // 'identifier' '*' 'identifier' followed by not '=' -- this
909 // '*' has to be a binary operator but determineStarAmpUsage() will
910 // categorize it as an unary operator, so set the right type here.
911 if (LookForDecls && !CurrentToken->Children.empty()) {
912 AnnotatedToken &Prev = *CurrentToken->Parent;
913 AnnotatedToken &Next = CurrentToken->Children[0];
914 if (Prev.Parent->is(tok::identifier) &&
915 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
916 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
917 Prev.Type = TT_BinaryOperator;
918 LookForDecls = false;
919 }
920 }
921
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000922 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000923 Left->MatchingParen = CurrentToken;
924 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000925
926 if (StartsObjCMethodExpr)
927 objCSelector.markEnd(*CurrentToken);
928
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 next();
930 return true;
931 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000933 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000934 if (!consumeToken())
935 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000936 }
937 return false;
938 }
939
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000940 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000941 if (!CurrentToken)
942 return false;
943
944 // A '[' could be an index subscript (after an indentifier or after
945 // ')' or ']'), or it could be the start of an Objective-C method
946 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000947 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000948 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000949 !Left->Parent || Left->Parent->is(tok::colon) ||
950 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
951 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
952 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000953 true, true) > prec::Unknown;
954
Nico Weber250fe712013-01-18 02:43:57 +0000955 ObjCSelectorRAII objCSelector(*this);
956 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000957 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000958
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000959 while (CurrentToken != NULL) {
960 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000961 if (!CurrentToken->Children.empty() &&
962 CurrentToken->Children[0].is(tok::l_paren)) {
963 // An ObjC method call can't be followed by an open parenthesis.
964 // FIXME: Do we incorrectly label ":" with this?
965 StartsObjCMethodExpr = false;
966 Left->Type = TT_Unknown;
967 }
Nico Weber250fe712013-01-18 02:43:57 +0000968 if (StartsObjCMethodExpr)
969 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000970 Left->MatchingParen = CurrentToken;
971 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000972 next();
973 return true;
974 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000975 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000976 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000977 if (!consumeToken())
978 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000979 }
980 return false;
981 }
982
Daniel Jasper83a54d22013-01-10 09:26:47 +0000983 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000984 // Lines are fine to end with '{'.
985 if (CurrentToken == NULL)
986 return true;
987 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000988 while (CurrentToken != NULL) {
989 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000990 Left->MatchingParen = CurrentToken;
991 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000992 next();
993 return true;
994 }
995 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
996 return false;
997 if (!consumeToken())
998 return false;
999 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001000 return true;
1001 }
1002
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001003 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001004 while (CurrentToken != NULL) {
1005 if (CurrentToken->is(tok::colon)) {
1006 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 next();
1008 return true;
1009 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001010 if (!consumeToken())
1011 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001012 }
1013 return false;
1014 }
1015
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001016 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001017 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1018 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001019 next();
1020 if (!parseAngle())
1021 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001022 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001023 return true;
1024 }
1025 return false;
1026 }
1027
Daniel Jasperc0880a92013-01-04 18:52:56 +00001028 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001029 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001030 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001031 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001032 case tok::plus:
1033 case tok::minus:
1034 // At the start of the line, +/- specific ObjectiveC method
1035 // declarations.
1036 if (Tok->Parent == NULL)
1037 Tok->Type = TT_ObjCMethodSpecifier;
1038 break;
Nico Webera7252d82013-01-12 06:18:40 +00001039 case tok::colon:
1040 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001041 if (Tok->Parent->is(tok::r_paren))
1042 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001043 if (ColonIsObjCMethodExpr)
1044 Tok->Type = TT_ObjCMethodExpr;
1045 break;
Nico Weber80a82762013-01-17 17:17:19 +00001046 case tok::kw_if:
1047 case tok::kw_while:
1048 if (CurrentToken->is(tok::l_paren)) {
1049 next();
1050 if (!parseParens(/*LookForDecls=*/true))
1051 return false;
1052 }
1053 break;
Nico Webera5510af2013-01-18 05:50:57 +00001054 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001055 if (!parseParens())
1056 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001057 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001058 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001059 if (!parseSquare())
1060 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001061 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001062 case tok::l_brace:
1063 if (!parseBrace())
1064 return false;
1065 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001067 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001068 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001069 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001070 Tok->Type = TT_BinaryOperator;
1071 CurrentToken = Tok;
1072 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001073 }
1074 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001075 case tok::r_paren:
1076 case tok::r_square:
1077 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001078 case tok::r_brace:
1079 // Lines can start with '}'.
1080 if (Tok->Parent != NULL)
1081 return false;
1082 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001084 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001085 break;
1086 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001087 if (CurrentToken->is(tok::l_paren)) {
1088 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001089 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001090 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1091 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001092 next();
1093 }
1094 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001095 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1096 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001097 next();
1098 }
1099 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 break;
1101 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001102 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001103 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001104 case tok::kw_template:
1105 parseTemplateDeclaration();
1106 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001107 default:
1108 break;
1109 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001110 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001111 }
1112
Daniel Jasper050948a52012-12-21 17:58:39 +00001113 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001114 next();
1115 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1116 next();
1117 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001118 if (CurrentToken->isNot(tok::comment) ||
1119 !CurrentToken->Children.empty())
1120 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001121 next();
1122 }
1123 } else {
1124 while (CurrentToken != NULL) {
1125 next();
1126 }
1127 }
1128 }
1129
1130 void parseWarningOrError() {
1131 next();
1132 // We still want to format the whitespace left of the first token of the
1133 // warning or error.
1134 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001135 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001136 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001137 next();
1138 }
1139 }
1140
1141 void parsePreprocessorDirective() {
1142 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001143 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001144 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001145 // Hashes in the middle of a line can lead to any strange token
1146 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001147 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001148 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001149 switch (
1150 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001151 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001152 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001153 parseIncludeDirective();
1154 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001155 case tok::pp_error:
1156 case tok::pp_warning:
1157 parseWarningOrError();
1158 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001159 default:
1160 break;
1161 }
1162 }
1163
Daniel Jasperda16db32013-01-07 10:48:50 +00001164 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001165 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001166 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001167 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001168 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001169 while (CurrentToken != NULL) {
1170 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001171 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001172 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001173 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001174 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001175 if (KeywordVirtualFound)
1176 return LT_VirtualFunctionDecl;
1177 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001178 }
1179
1180 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001181 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1182 CurrentToken = &CurrentToken->Children[0];
1183 else
1184 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001185 }
1186
1187 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001188 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001189 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001190 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001191 };
1192
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001193 void calculateExtraInformation(AnnotatedToken &Current) {
1194 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1195
Manuel Klimek52b15152013-01-09 15:25:02 +00001196 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001197 Current.MustBreakBefore = true;
1198 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001199 if (Current.Type == TT_LineComment) {
1200 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001201 } else if ((Current.Parent->is(tok::comment) &&
1202 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001203 (Current.is(tok::string_literal) &&
1204 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001205 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001206 } else {
1207 Current.MustBreakBefore = false;
1208 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001209 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001210 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001211 if (Current.MustBreakBefore)
1212 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1213 else
1214 Current.TotalLength = Current.Parent->TotalLength +
1215 Current.FormatTok.TokenLength +
1216 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001217 if (!Current.Children.empty())
1218 calculateExtraInformation(Current.Children[0]);
1219 }
1220
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001221 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001222 AnnotatingParser Parser(Line.First);
1223 Line.Type = Parser.parseLine();
1224 if (Line.Type == LT_Invalid)
1225 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001226
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001227 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001228
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001229 if (Line.First.Type == TT_ObjCMethodSpecifier)
1230 Line.Type = LT_ObjCMethodDecl;
1231 else if (Line.First.Type == TT_ObjCDecl)
1232 Line.Type = LT_ObjCDecl;
1233 else if (Line.First.Type == TT_ObjCProperty)
1234 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001235
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001236 Line.First.SpaceRequiredBefore = true;
1237 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1238 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001239
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001240 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001241 if (!Line.First.Children.empty())
1242 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001243 }
1244
1245private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001246 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1247 if (getPrecedence(Current) == prec::Assignment ||
1248 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1249 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001250
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001251 if (Current.Type == TT_Unknown) {
1252 if (Current.is(tok::star) || Current.is(tok::amp)) {
1253 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001254 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1255 Current.is(tok::caret)) {
1256 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001257 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1258 Current.Type = determineIncrementUsage(Current);
1259 } else if (Current.is(tok::exclaim)) {
1260 Current.Type = TT_UnaryOperator;
1261 } else if (isBinaryOperator(Current)) {
1262 Current.Type = TT_BinaryOperator;
1263 } else if (Current.is(tok::comment)) {
1264 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1265 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001266 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001267 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001268 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001269 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001270 } else if (Current.is(tok::r_paren) &&
1271 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001272 Current.Parent->Type == TT_TemplateCloser) &&
1273 (Current.Children.empty() ||
1274 (Current.Children[0].isNot(tok::equal) &&
1275 Current.Children[0].isNot(tok::semi) &&
1276 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001277 // FIXME: We need to get smarter and understand more cases of casts.
1278 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001279 } else if (Current.is(tok::at) && Current.Children.size()) {
1280 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1281 case tok::objc_interface:
1282 case tok::objc_implementation:
1283 case tok::objc_protocol:
1284 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001285 break;
1286 case tok::objc_property:
1287 Current.Type = TT_ObjCProperty;
1288 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001289 default:
1290 break;
1291 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001292 }
1293 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001294
1295 if (!Current.Children.empty())
1296 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001297 }
1298
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001299 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001300 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001301 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001302 }
1303
Daniel Jasper71945272013-01-15 14:27:39 +00001304 /// \brief Returns the previous token ignoring comments.
1305 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1306 const AnnotatedToken *PrevToken = Tok.Parent;
1307 while (PrevToken != NULL && PrevToken->is(tok::comment))
1308 PrevToken = PrevToken->Parent;
1309 return PrevToken;
1310 }
1311
1312 /// \brief Returns the next token ignoring comments.
1313 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1314 if (Tok.Children.empty())
1315 return NULL;
1316 const AnnotatedToken *NextToken = &Tok.Children[0];
1317 while (NextToken->is(tok::comment)) {
1318 if (NextToken->Children.empty())
1319 return NULL;
1320 NextToken = &NextToken->Children[0];
1321 }
1322 return NextToken;
1323 }
1324
1325 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001326 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001327 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1328 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001329 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001330
1331 const AnnotatedToken *NextToken = getNextToken(Tok);
1332 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001333 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001334
Daniel Jasper0b820602013-01-22 11:46:26 +00001335 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1336 return TT_PointerOrReference;
1337
Daniel Jasper71945272013-01-15 14:27:39 +00001338 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1339 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1340 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1341 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001342 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001343 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001344
Daniel Jasper71945272013-01-15 14:27:39 +00001345 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1346 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1347 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1348 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1349 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1350 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1351 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001352 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001353
Daniel Jasper71945272013-01-15 14:27:39 +00001354 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1355 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001356 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001357
Daniel Jasper426702d2012-12-05 07:51:39 +00001358 // It is very unlikely that we are going to find a pointer or reference type
1359 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001360 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001361 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001362
Daniel Jasperda16db32013-01-07 10:48:50 +00001363 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001364 }
1365
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001366 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001367 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1368 if (PrevToken == NULL)
1369 return TT_UnaryOperator;
1370
Daniel Jasper8dd40472012-12-21 09:41:31 +00001371 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001372 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1373 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1374 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1375 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1376 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001377 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001378
1379 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001380 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001381 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001382
1383 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001384 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001385 }
1386
1387 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001388 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001389 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1390 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001391 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001392 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1393 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001394 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001395
Daniel Jasperda16db32013-01-07 10:48:50 +00001396 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001397 }
1398
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001399 bool spaceRequiredBetween(const AnnotatedToken &Left,
1400 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001401 if (Right.is(tok::hashhash))
1402 return Left.is(tok::hash);
1403 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1404 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001405 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1406 return false;
Nico Webera6087752013-01-10 20:12:55 +00001407 if (Right.is(tok::less) &&
1408 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001409 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001410 return true;
1411 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1412 return false;
1413 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1414 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001415 if (Left.is(tok::at) &&
1416 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1417 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001418 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1419 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001420 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001421 if (Left.is(tok::coloncolon))
1422 return false;
1423 if (Right.is(tok::coloncolon))
1424 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001425 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1426 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001427 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001428 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001429 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1430 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001431 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001432 return Right.FormatTok.Tok.isLiteral() ||
1433 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001434 if (Right.is(tok::star) && Left.is(tok::l_paren))
1435 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001436 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1437 return false;
1438 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001439 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001440 if (Left.is(tok::period) || Right.is(tok::period))
1441 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001442 if (Left.is(tok::colon))
1443 return Left.Type != TT_ObjCMethodExpr;
1444 if (Right.is(tok::colon))
1445 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001446 if (Left.is(tok::l_paren))
1447 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001448 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001449 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001450 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001451 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001452 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1453 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001454 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001455 if (Left.is(tok::at) &&
1456 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001457 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001458 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1459 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001460 return true;
1461 }
1462
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001463 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001464 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001465 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1466 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001467 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001468 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001469 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001470 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001471 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001472 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001473 // Don't space between ')' and <id>
1474 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001475 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001476 // Don't space between ':' and '('
1477 return false;
1478 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001479 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001480 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1481 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001482
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001483 if (Tok.Parent->is(tok::comma))
1484 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001485 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001486 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001487 if (Tok.Type == TT_OverloadedOperator)
1488 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001489 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001490 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001491 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001492 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001493 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001494 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001495 if (Tok.Parent->Type == TT_UnaryOperator ||
1496 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001497 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001498 if (Tok.Type == TT_UnaryOperator)
1499 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001500 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1501 (Tok.Parent->isNot(tok::colon) ||
1502 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001503 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1504 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001505 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1506 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001507 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001508 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001509 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001510 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001511 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001512 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001513 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001514 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001515 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001516 }
1517
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001518 bool canBreakBefore(const AnnotatedToken &Right) {
1519 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001520 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001521 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1522 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001523 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001524 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1525 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001526 // Don't break this identifier as ':' or identifier
1527 // before it will break.
1528 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001529 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1530 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001531 // Don't break at ':' if identifier before it can beak.
1532 return false;
1533 }
Nico Webera7252d82013-01-12 06:18:40 +00001534 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1535 return false;
1536 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1537 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001538 if (isObjCSelectorName(Right))
1539 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001540 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001541 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001542 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001543 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001544 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001545 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001546 return false;
1547
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001548 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001549 // We rely on MustBreakBefore being set correctly here as we should not
1550 // change the "binding" behavior of a comment.
1551 return false;
1552
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001553 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1554 // unless it is follow by ';', '{' or '='.
1555 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1556 Left.Parent->is(tok::r_paren))
1557 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1558 Right.isNot(tok::equal);
1559
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001560 // We only break before r_brace if there was a corresponding break before
1561 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1562 if (Right.is(tok::r_brace))
1563 return false;
1564
Daniel Jasper71945272013-01-15 14:27:39 +00001565 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001566 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001567 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1568 Left.is(tok::comma) || Right.is(tok::lessless) ||
1569 Right.is(tok::arrow) || Right.is(tok::period) ||
1570 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001571 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1572 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1573 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001574 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001575 }
1576
Daniel Jasperf7935112012-12-03 18:12:45 +00001577 FormatStyle Style;
1578 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001579 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001580 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001581};
1582
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001583class LexerBasedFormatTokenSource : public FormatTokenSource {
1584public:
1585 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001586 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001587 IdentTable(Lex.getLangOpts()) {
1588 Lex.SetKeepWhitespaceMode(true);
1589 }
1590
1591 virtual FormatToken getNextToken() {
1592 if (GreaterStashed) {
1593 FormatTok.NewlinesBefore = 0;
1594 FormatTok.WhiteSpaceStart =
1595 FormatTok.Tok.getLocation().getLocWithOffset(1);
1596 FormatTok.WhiteSpaceLength = 0;
1597 GreaterStashed = false;
1598 return FormatTok;
1599 }
1600
1601 FormatTok = FormatToken();
1602 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001603 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001604 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001605 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1606 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001607
1608 // Consume and record whitespace until we find a significant token.
1609 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001610 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001611 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1612 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001613 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1614
1615 if (FormatTok.Tok.is(tok::eof))
1616 return FormatTok;
1617 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001618 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001619 }
Manuel Klimekef920692013-01-07 07:56:50 +00001620
1621 // Now FormatTok is the next non-whitespace token.
1622 FormatTok.TokenLength = Text.size();
1623
Manuel Klimek1abf7892013-01-04 23:34:14 +00001624 // In case the token starts with escaped newlines, we want to
1625 // take them into account as whitespace - this pattern is quite frequent
1626 // in macro definitions.
1627 // FIXME: What do we want to do with other escaped spaces, and escaped
1628 // spaces or newlines in the middle of tokens?
1629 // FIXME: Add a more explicit test.
1630 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001631 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001632 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001633 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001634 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001635 }
1636
1637 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001638 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001639 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001640 FormatTok.Tok.setKind(Info.getTokenID());
1641 }
1642
1643 if (FormatTok.Tok.is(tok::greatergreater)) {
1644 FormatTok.Tok.setKind(tok::greater);
1645 GreaterStashed = true;
1646 }
1647
1648 return FormatTok;
1649 }
1650
1651private:
1652 FormatToken FormatTok;
1653 bool GreaterStashed;
1654 Lexer &Lex;
1655 SourceManager &SourceMgr;
1656 IdentifierTable IdentTable;
1657
1658 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001659 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001660 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1661 Tok.getLength());
1662 }
1663};
1664
Daniel Jasperf7935112012-12-03 18:12:45 +00001665class Formatter : public UnwrappedLineConsumer {
1666public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001667 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1668 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001669 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001670 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001671 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001672
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001673 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001674
Daniel Jasperf7935112012-12-03 18:12:45 +00001675 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001676 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001677 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001678 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001679 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001680 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1681 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1682 Annotator.annotate();
1683 }
1684 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1685 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001686 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001687 const AnnotatedLine &TheLine = *I;
1688 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1689 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1690 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001691 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001692 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001693 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001694 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001695 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001696 PreviousEndOfLineColumn = Formatter.format();
1697 } else {
1698 // If we did not reformat this unwrapped line, the column at the end of
1699 // the last token is unchanged - thus, we can calculate the end of the
1700 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001701 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001702 SourceMgr.getSpellingColumnNumber(
1703 TheLine.Last->FormatTok.Tok.getLocation()) +
1704 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1705 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001706 1;
1707 }
1708 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001709 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001710 }
1711
1712private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001713 /// \brief Tries to merge lines into one.
1714 ///
1715 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1716 /// if possible; note that \c I will be incremented when lines are merged.
1717 ///
1718 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001719 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001720 std::vector<AnnotatedLine>::iterator &I,
1721 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001722 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1723
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001724 // We can never merge stuff if there are trailing line comments.
1725 if (I->Last->Type == TT_LineComment)
1726 return;
1727
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001728 // Check whether the UnwrappedLine can be put onto a single line. If
1729 // so, this is bound to be the optimal solution (by definition) and we
1730 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001731 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001732 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001733 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001734
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001735 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001736 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001737
Daniel Jasper25837aa2013-01-14 14:14:23 +00001738 if (I->Last->is(tok::l_brace)) {
1739 tryMergeSimpleBlock(I, E, Limit);
1740 } else if (I->First.is(tok::kw_if)) {
1741 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001742 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1743 I->First.FormatTok.IsFirst)) {
1744 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001745 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001746 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001747 }
1748
Daniel Jasper39825ea2013-01-14 15:40:57 +00001749 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1750 std::vector<AnnotatedLine>::iterator E,
1751 unsigned Limit) {
1752 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001753 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1754 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001755 if (I + 2 != E && (I + 2)->InPPDirective &&
1756 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1757 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001758 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001759 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001760 join(Line, *(++I));
1761 }
1762
Daniel Jasper25837aa2013-01-14 14:14:23 +00001763 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1764 std::vector<AnnotatedLine>::iterator E,
1765 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001766 if (!Style.AllowShortIfStatementsOnASingleLine)
1767 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001768 if ((I + 1)->InPPDirective != I->InPPDirective ||
1769 ((I + 1)->InPPDirective &&
1770 (I + 1)->First.FormatTok.HasUnescapedNewline))
1771 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001772 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001773 if (Line.Last->isNot(tok::r_paren))
1774 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001775 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001776 return;
1777 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1778 return;
1779 // Only inline simple if's (no nested if or else).
1780 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1781 return;
1782 join(Line, *(++I));
1783 }
1784
1785 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1786 std::vector<AnnotatedLine>::iterator E,
1787 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001788 // First, check that the current line allows merging. This is the case if
1789 // we're not in a control flow statement and the last token is an opening
1790 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001791 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001792 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001793 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1794 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1795 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1796 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001797 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001798 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1799 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001800 if (!AllowedTokens)
1801 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001802
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001803 AnnotatedToken *Tok = &(I + 1)->First;
1804 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1805 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1806 Tok->SpaceRequiredBefore = false;
1807 join(Line, *(I + 1));
1808 I += 1;
1809 } else {
1810 // Check that we still have three lines and they fit into the limit.
1811 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1812 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001813 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001814
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001815 // Second, check that the next line does not contain any braces - if it
1816 // does, readability declines when putting it into a single line.
1817 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1818 return;
1819 do {
1820 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1821 return;
1822 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1823 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001824
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001825 // Last, check that the third line contains a single closing brace.
1826 Tok = &(I + 2)->First;
1827 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1828 Tok->MustBreakBefore)
1829 return;
1830
1831 join(Line, *(I + 1));
1832 join(Line, *(I + 2));
1833 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001834 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001835 }
1836
1837 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1838 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001839 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1840 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001841 }
1842
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001843 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1844 A.Last->Children.push_back(B.First);
1845 while (!A.Last->Children.empty()) {
1846 A.Last->Children[0].Parent = A.Last;
1847 A.Last = &A.Last->Children[0];
1848 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001849 }
1850
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001851 bool touchesRanges(const AnnotatedLine &TheLine) {
1852 const FormatToken *First = &TheLine.First.FormatTok;
1853 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001854 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001855 First->Tok.getLocation(),
1856 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001857 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001858 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1859 Ranges[i].getBegin()) &&
1860 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1861 LineRange.getBegin()))
1862 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001863 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001864 return false;
1865 }
1866
1867 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001868 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001869 }
1870
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001871 /// \brief Add a new line and the required indent before the first Token
1872 /// of the \c UnwrappedLine if there was no structural parsing error.
1873 /// Returns the indent level of the \c UnwrappedLine.
1874 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1875 bool InPPDirective,
1876 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001877 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001878 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1879 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1880
1881 unsigned Newlines = std::min(Tok.NewlinesBefore,
1882 Style.MaxEmptyLinesToKeep + 1);
1883 if (Newlines == 0 && !Tok.IsFirst)
1884 Newlines = 1;
1885 unsigned Indent = Level * 2;
1886
1887 bool IsAccessModifier = false;
1888 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1889 RootToken.is(tok::kw_private))
1890 IsAccessModifier = true;
1891 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1892 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1893 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1894 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1895 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1896 IsAccessModifier = true;
1897
1898 if (IsAccessModifier &&
1899 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1900 Indent += Style.AccessModifierOffset;
1901 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001902 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001903 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001904 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1905 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001906 }
1907 return Indent;
1908 }
1909
Alexander Kornienko116ba682013-01-14 11:34:14 +00001910 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001911 FormatStyle Style;
1912 Lexer &Lex;
1913 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001914 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001915 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001916 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001917 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001918};
1919
1920tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1921 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001922 std::vector<CharSourceRange> Ranges,
1923 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001924 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001925 OwningPtr<DiagnosticConsumer> DiagPrinter;
1926 if (DiagClient == 0) {
1927 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1928 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1929 DiagClient = DiagPrinter.get();
1930 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001931 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001932 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001933 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001934 Diagnostics.setSourceManager(&SourceMgr);
1935 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001936 return formatter.format();
1937}
1938
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001939LangOptions getFormattingLangOpts() {
1940 LangOptions LangOpts;
1941 LangOpts.CPlusPlus = 1;
1942 LangOpts.CPlusPlus11 = 1;
1943 LangOpts.Bool = 1;
1944 LangOpts.ObjC1 = 1;
1945 LangOpts.ObjC2 = 1;
1946 return LangOpts;
1947}
1948
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001949} // namespace format
1950} // namespace clang