blob: bae1bbb86d943b5a8e6f3b2612261a3a3409ad01 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
Daniel Jasper50e7ab72013-01-22 14:28:24 +000063 LT_BuilderTypeCall,
Daniel Jasperda16db32013-01-07 10:48:50 +000064 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000069};
70
Daniel Jasper7c85fde2013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000073 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper7b5773e92013-01-28 07:35:34 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL),
77 ParameterCount(1), Parent(NULL) {
78 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +000079
Daniel Jasper25837aa2013-01-14 14:14:23 +000080 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
81 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
82
Daniel Jasper7c85fde2013-01-08 14:56:18 +000083 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
84 return FormatTok.Tok.isObjCAtKeyword(Kind);
85 }
86
87 FormatToken FormatTok;
88
Daniel Jasperf7935112012-12-03 18:12:45 +000089 TokenType Type;
90
Daniel Jasperf7935112012-12-03 18:12:45 +000091 bool SpaceRequiredBefore;
92 bool CanBreakBefore;
93 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000094
95 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000096
Daniel Jasper9278eb92013-01-16 14:59:02 +000097 AnnotatedToken *MatchingParen;
98
Daniel Jasper7b5773e92013-01-28 07:35:34 +000099 /// \brief Number of parameters, if this is "(", "[" or "<".
100 ///
101 /// This is initialized to 1 as we don't need to distinguish functions with
102 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
103 /// the number of commas.
104 unsigned ParameterCount;
105
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000106 /// \brief The total length of the line up to and including this token.
107 unsigned TotalLength;
108
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000109 std::vector<AnnotatedToken> Children;
110 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000111
112 const AnnotatedToken *getPreviousNoneComment() const {
113 AnnotatedToken *Tok = Parent;
114 while (Tok != NULL && Tok->is(tok::comment))
115 Tok = Tok->Parent;
116 return Tok;
117 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000118};
119
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000120class AnnotatedLine {
121public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000122 AnnotatedLine(const UnwrappedLine &Line)
123 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000124 InPPDirective(Line.InPPDirective),
125 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000126 assert(!Line.Tokens.empty());
127 AnnotatedToken *Current = &First;
128 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
129 E = Line.Tokens.end();
130 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000131 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000132 Current->Children[0].Parent = Current;
133 Current = &Current->Children[0];
134 }
135 Last = Current;
136 }
137 AnnotatedLine(const AnnotatedLine &Other)
138 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000139 InPPDirective(Other.InPPDirective),
140 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000141 Last = &First;
142 while (!Last->Children.empty()) {
143 Last->Children[0].Parent = Last;
144 Last = &Last->Children[0];
145 }
146 }
147
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000148 AnnotatedToken First;
149 AnnotatedToken *Last;
150
151 LineType Type;
152 unsigned Level;
153 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000154 bool MustBeDeclaration;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000155};
156
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000157static prec::Level getPrecedence(const AnnotatedToken &Tok) {
158 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000159}
160
Daniel Jasperf7935112012-12-03 18:12:45 +0000161FormatStyle getLLVMStyle() {
162 FormatStyle LLVMStyle;
163 LLVMStyle.ColumnLimit = 80;
164 LLVMStyle.MaxEmptyLinesToKeep = 1;
165 LLVMStyle.PointerAndReferenceBindToType = false;
166 LLVMStyle.AccessModifierOffset = -2;
167 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000168 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000169 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000170 LLVMStyle.BinPackParameters = true;
Daniel Jaspere941b162013-01-23 10:08:28 +0000171 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000172 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000173 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000174 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000175 return LLVMStyle;
176}
177
178FormatStyle getGoogleStyle() {
179 FormatStyle GoogleStyle;
180 GoogleStyle.ColumnLimit = 80;
181 GoogleStyle.MaxEmptyLinesToKeep = 1;
182 GoogleStyle.PointerAndReferenceBindToType = true;
183 GoogleStyle.AccessModifierOffset = -1;
184 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000185 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000186 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000187 GoogleStyle.BinPackParameters = false;
Daniel Jaspere941b162013-01-23 10:08:28 +0000188 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000189 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000190 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000191 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000192 return GoogleStyle;
193}
194
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000195FormatStyle getChromiumStyle() {
196 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jaspere941b162013-01-23 10:08:28 +0000197 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000198 return ChromiumStyle;
199}
200
Daniel Jasperf7935112012-12-03 18:12:45 +0000201struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000202 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000203 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000204 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000205};
206
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000207/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000208///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000209/// This includes special handling for certain constructs, e.g. the alignment of
210/// trailing line comments.
211class WhitespaceManager {
212public:
213 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
214
215 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
216 /// each \c AnnotatedToken.
217 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
218 unsigned Spaces, unsigned WhitespaceStartColumn,
219 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000220 // 2+ newlines mean an empty line separating logic scopes.
221 if (NewLines >= 2)
222 alignComments();
223
224 // Align line comments if they are trailing or if they continue other
225 // trailing comments.
226 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000227 (Tok.Parent != NULL || !Comments.empty())) {
228 if (Style.ColumnLimit >=
229 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
230 Comments.push_back(StoredComment());
231 Comments.back().Tok = Tok.FormatTok;
232 Comments.back().Spaces = Spaces;
233 Comments.back().NewLines = NewLines;
234 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
235 Comments.back().MaxColumn = Style.ColumnLimit -
236 Spaces - Tok.FormatTok.TokenLength;
237 return;
238 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000239 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000240
241 // If this line does not have a trailing comment, align the stored comments.
242 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
243 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000244 storeReplacement(Tok.FormatTok,
245 std::string(NewLines, '\n') + std::string(Spaces, ' '));
246 }
247
248 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
249 /// backslashes to escape newlines inside a preprocessor directive.
250 ///
251 /// This function and \c replaceWhitespace have the same behavior if
252 /// \c Newlines == 0.
253 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
254 unsigned Spaces, unsigned WhitespaceStartColumn,
255 const FormatStyle &Style) {
256 std::string NewLineText;
257 if (NewLines > 0) {
258 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
259 WhitespaceStartColumn);
260 for (unsigned i = 0; i < NewLines; ++i) {
261 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
262 NewLineText += "\\\n";
263 Offset = 0;
264 }
265 }
266 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
267 }
268
269 /// \brief Returns all the \c Replacements created during formatting.
270 const tooling::Replacements &generateReplacements() {
271 alignComments();
272 return Replaces;
273 }
274
275private:
276 /// \brief Structure to store a comment for later layout and alignment.
277 struct StoredComment {
278 FormatToken Tok;
279 unsigned MinColumn;
280 unsigned MaxColumn;
281 unsigned NewLines;
282 unsigned Spaces;
283 };
284 SmallVector<StoredComment, 16> Comments;
285 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
286
287 /// \brief Try to align all stashed comments.
288 void alignComments() {
289 unsigned MinColumn = 0;
290 unsigned MaxColumn = UINT_MAX;
291 comment_iterator Start = Comments.begin();
292 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
293 ++I) {
294 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
295 alignComments(Start, I, MinColumn);
296 MinColumn = I->MinColumn;
297 MaxColumn = I->MaxColumn;
298 Start = I;
299 } else {
300 MinColumn = std::max(MinColumn, I->MinColumn);
301 MaxColumn = std::min(MaxColumn, I->MaxColumn);
302 }
303 }
304 alignComments(Start, Comments.end(), MinColumn);
305 Comments.clear();
306 }
307
308 /// \brief Put all the comments between \p I and \p E into \p Column.
309 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
310 while (I != E) {
311 unsigned Spaces = I->Spaces + Column - I->MinColumn;
312 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
313 std::string(Spaces, ' '));
314 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000315 }
316 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000317
318 /// \brief Stores \p Text as the replacement for the whitespace in front of
319 /// \p Tok.
320 void storeReplacement(const FormatToken &Tok, const std::string Text) {
321 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
322 Tok.WhiteSpaceLength, Text));
323 }
324
325 SourceManager &SourceMgr;
326 tooling::Replacements Replaces;
327};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000328
Nico Weberc9d73612013-01-12 22:48:47 +0000329/// \brief Returns if a token is an Objective-C selector name.
330///
Nico Weber92c05392013-01-12 22:51:13 +0000331/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000332static bool isObjCSelectorName(const AnnotatedToken &Tok) {
333 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
334 Tok.Children[0].is(tok::colon) &&
335 Tok.Children[0].Type == TT_ObjCMethodExpr;
336}
337
Daniel Jasperf7935112012-12-03 18:12:45 +0000338class UnwrappedLineFormatter {
339public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000340 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000341 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000342 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000343 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000344 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000345 FirstIndent(FirstIndent), RootToken(RootToken),
346 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000347 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000348 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000349 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 }
351
Manuel Klimek1abf7892013-01-04 23:34:14 +0000352 /// \brief Formats an \c UnwrappedLine.
353 ///
354 /// \returns The column after the last token in the last line of the
355 /// \c UnwrappedLine.
356 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000357 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000358 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000359 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000360 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000361 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000362 State.ForLoopVariablePos = 0;
363 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000364 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000365
Manuel Klimek24998102013-01-16 14:55:28 +0000366 DEBUG({
367 DebugTokenState(*State.NextToken);
368 });
369
Daniel Jaspere9de2602012-12-06 09:56:08 +0000370 // The first token has already been indented and thus consumed.
371 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000372
373 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000374 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000375 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
376 // Calculating the column is important for aligning trailing comments.
377 // FIXME: This does not seem to happen in conjunction with escaped
378 // newlines. If it does, fix!
379 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
380 State.NextToken->FormatTok.TokenLength;
381 State.NextToken = State.NextToken->Children.empty() ? NULL :
382 &State.NextToken->Children[0];
383 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000384 addTokenToState(false, false, State);
385 } else {
386 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
387 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000388 DEBUG({
389 if (Break < NoBreak)
390 llvm::errs() << "\n";
391 else
392 llvm::errs() << " ";
393 llvm::errs() << "<";
394 DebugPenalty(Break, Break < NoBreak);
395 llvm::errs() << "/";
396 DebugPenalty(NoBreak, !(Break < NoBreak));
397 llvm::errs() << "> ";
398 DebugTokenState(*State.NextToken);
399 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000400 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000401 if (State.NextToken != NULL &&
402 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
403 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000404 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000405 State.Stack.back().BreakAfterComma = true;
406 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000407 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000408 }
Manuel Klimek24998102013-01-16 14:55:28 +0000409 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000410 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000411 }
412
413private:
Manuel Klimek24998102013-01-16 14:55:28 +0000414 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
415 const Token &Tok = AnnotatedTok.FormatTok.Tok;
416 llvm::errs()
417 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
418 Tok.getLength());
419 llvm::errs();
420 }
421
422 void DebugPenalty(unsigned Penalty, bool Winner) {
423 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
424 if (Penalty == UINT_MAX)
425 llvm::errs() << "MAX";
426 else
427 llvm::errs() << Penalty;
428 llvm::errs().resetColor();
429 }
430
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000432 ParenState(unsigned Indent, unsigned LastSpace)
Daniel Jaspera836b902013-01-23 16:58:21 +0000433 : Indent(Indent), LastSpace(LastSpace), AssignmentColumn(0),
434 FirstLessLess(0), BreakBeforeClosingBrace(false),
435 BreakAfterComma(false), HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000436
Daniel Jasperf7935112012-12-03 18:12:45 +0000437 /// \brief The position to which a specific parenthesis level needs to be
438 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000439 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000440
Daniel Jaspere9de2602012-12-06 09:56:08 +0000441 /// \brief The position of the last space on each level.
442 ///
443 /// Used e.g. to break like:
444 /// functionCall(Parameter, otherCall(
445 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000446 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000447
Daniel Jaspera836b902013-01-23 16:58:21 +0000448 /// \brief This is the column of the first token after an assignment.
449 unsigned AssignmentColumn;
450
Daniel Jaspere9de2602012-12-06 09:56:08 +0000451 /// \brief The position the first "<<" operator encountered on each level.
452 ///
453 /// Used to align "<<" operators. 0 if no such operator has been encountered
454 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000455 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000456
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000457 /// \brief Whether a newline needs to be inserted before the block's closing
458 /// brace.
459 ///
460 /// We only want to insert a newline before the closing brace if there also
461 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000462 bool BreakBeforeClosingBrace;
463
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000464 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000465 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000466
Daniel Jasper337816e2013-01-11 10:22:12 +0000467 bool operator<(const ParenState &Other) const {
468 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000469 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000470 if (LastSpace != Other.LastSpace)
471 return LastSpace < Other.LastSpace;
Daniel Jaspera836b902013-01-23 16:58:21 +0000472 if (AssignmentColumn != Other.AssignmentColumn)
473 return AssignmentColumn < Other.AssignmentColumn;
Daniel Jasper337816e2013-01-11 10:22:12 +0000474 if (FirstLessLess != Other.FirstLessLess)
475 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000476 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
477 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000478 if (BreakAfterComma != Other.BreakAfterComma)
479 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000480 if (HasMultiParameterLine != Other.HasMultiParameterLine)
481 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000482 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000483 }
484 };
485
486 /// \brief The current state when indenting a unwrapped line.
487 ///
488 /// As the indenting tries different combinations this is copied by value.
489 struct LineState {
490 /// \brief The number of used columns in the current line.
491 unsigned Column;
492
493 /// \brief The token that needs to be next formatted.
494 const AnnotatedToken *NextToken;
495
496 /// \brief The parenthesis level of the first token on the current line.
497 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000498
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 /// \brief The column of the first variable in a for-loop declaration.
500 ///
501 /// Used to align the second variable if necessary.
502 unsigned ForLoopVariablePos;
503
504 /// \brief \c true if this line contains a continued for-loop section.
505 bool LineContainsContinuedForLoopSection;
506
Daniel Jasper337816e2013-01-11 10:22:12 +0000507 /// \brief A stack keeping track of properties applying to parenthesis
508 /// levels.
509 std::vector<ParenState> Stack;
510
511 /// \brief Comparison operator to be able to used \c LineState in \c map.
512 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000513 if (Other.NextToken != NextToken)
514 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000515 if (Other.Column != Column)
516 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000517 if (Other.StartOfLineLevel != StartOfLineLevel)
518 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000519 if (Other.ForLoopVariablePos != ForLoopVariablePos)
520 return Other.ForLoopVariablePos < ForLoopVariablePos;
521 if (Other.LineContainsContinuedForLoopSection !=
522 LineContainsContinuedForLoopSection)
523 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000524 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000525 }
526 };
527
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000528 /// \brief Appends the next token to \p State and updates information
529 /// necessary for indentation.
530 ///
531 /// Puts the token on the current line if \p Newline is \c true and adds a
532 /// line break and necessary indentation otherwise.
533 ///
534 /// If \p DryRun is \c false, also creates and stores the required
535 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000536 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000537 const AnnotatedToken &Current = *State.NextToken;
538 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 assert(State.Stack.size());
540 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000541
542 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000543 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000544 if (Current.is(tok::r_brace)) {
545 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000546 } else if (Current.is(tok::string_literal) &&
547 Previous.is(tok::string_literal)) {
548 State.Column = State.Column - Previous.FormatTok.TokenLength;
549 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000550 State.Stack[ParenLevel].FirstLessLess != 0) {
551 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000552 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000553 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
554 Current.is(tok::period) || Previous.is(tok::question) ||
555 Previous.Type == TT_ConditionalExpr)) {
556 // Indent and extra 4 spaces after if we know the current expression is
557 // continued. Don't do that on the top level, as we already indent 4
558 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000559 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000560 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000561 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000562 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000563 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera836b902013-01-23 16:58:21 +0000564 } else if (Previous.Type == TT_BinaryOperator &&
565 State.Stack.back().AssignmentColumn != 0) {
566 State.Column = State.Stack.back().AssignmentColumn;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000567 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000568 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000569 }
570
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000571 // A line starting with a closing brace is assumed to be correct for the
572 // same level as before the opening brace.
573 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000574
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000575 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000576 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000577
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000578 if (!DryRun) {
579 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000580 Whitespaces.replaceWhitespace(Current, 1, State.Column,
581 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000582 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000583 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
584 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000585 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000586
Daniel Jasper337816e2013-01-11 10:22:12 +0000587 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000588 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000589 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000590 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000591 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
592 State.ForLoopVariablePos = State.Column -
593 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000594
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000595 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
596 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000597 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000598
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000600 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000601
Daniel Jasperbcab4302013-01-09 10:40:23 +0000602 // FIXME: Do we need to do this for assignments nested in other
603 // expressions?
604 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000605 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000606 Previous.is(tok::kw_return)))
Daniel Jaspera836b902013-01-23 16:58:21 +0000607 State.Stack.back().AssignmentColumn = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000608 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000609 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000610 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000611 if (Current.getPreviousNoneComment() != NULL &&
612 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000613 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000614 State.Stack[ParenLevel].HasMultiParameterLine = true;
615
Daniel Jaspere9de2602012-12-06 09:56:08 +0000616 State.Column += Spaces;
Daniel Jasper39e27382013-01-23 20:41:06 +0000617 if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
618 // Treat the condition inside an if as if it was a second function
619 // parameter, i.e. let nested calls have an indent of 4.
620 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
Daniel Jasper7a31af12013-01-25 15:43:32 +0000621 else if (Previous.is(tok::comma) && ParenLevel != 0)
Daniel Jasper39e27382013-01-23 20:41:06 +0000622 // Top-level spaces are exempt as that mostly leads to better results.
623 State.Stack.back().LastSpace = State.Column;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000624 else if (Previous.ParameterCount > 1 &&
625 (Previous.is(tok::l_paren) || Previous.is(tok::l_square) ||
626 Previous.Type == TT_TemplateOpener))
627 // If this function has multiple parameters, indent nested calls from
628 // the start of the first parameter.
629 State.Stack.back().LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000630 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000631
632 // If we break after an {, we should also break before the corresponding }.
633 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000634 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000635
Daniel Jaspere941b162013-01-23 10:08:28 +0000636 if (!Style.BinPackParameters && Newline) {
637 // If we are breaking after '(', '{', '<', this is not bin packing unless
638 // AllowAllParametersOnNextLine is false.
639 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
640 Previous.Type != TT_TemplateOpener) ||
641 !Style.AllowAllParametersOnNextLine)
642 State.Stack.back().BreakAfterComma = true;
643
644 // Any break on this level means that the parent level has been broken
645 // and we need to avoid bin packing there.
646 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
647 State.Stack[i].BreakAfterComma = true;
648 }
649 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000650
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000651 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000652 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000653
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 /// \brief Mark the next token as consumed in \p State and modify its stacks
655 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000656 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000657 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000658 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000659
Daniel Jasper337816e2013-01-11 10:22:12 +0000660 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
661 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000662
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000663 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000664 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000665 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
666 Current.is(tok::l_brace) ||
667 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000668 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000669 if (Current.is(tok::l_brace)) {
670 // FIXME: This does not work with nested static initializers.
671 // Implement a better handling for static initializers and similar
672 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000673 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000674 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000675 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000676 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000677 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000678 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000679 }
680
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000681 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000682 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000683 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
684 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
685 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000686 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000687 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000688
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000689 if (State.NextToken->Children.empty())
690 State.NextToken = NULL;
691 else
692 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000693
694 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000695 }
696
Nico Weber49cbc2c2013-01-07 15:15:29 +0000697 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000698 unsigned splitPenalty(const AnnotatedToken &Tok) {
699 const AnnotatedToken &Left = Tok;
700 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000701
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000702 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
703 return 50;
704 if (Left.is(tok::equal) && Right.is(tok::l_brace))
705 return 150;
Daniel Jasper45797022013-01-25 10:57:27 +0000706 if (Left.is(tok::coloncolon))
707 return 500;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000708
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000709 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000710 if (RootToken.is(tok::kw_for) &&
711 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000712 return 20;
713
Daniel Jasper04468962013-01-18 10:56:38 +0000714 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000716
717 // In Objective-C method expressions, prefer breaking before "param:" over
718 // breaking after it.
719 if (isObjCSelectorName(Right))
720 return 0;
721 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
722 return 20;
723
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000724 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000725 return 20;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000726 // FIXME: The penalty for a trailing "<" or "[" being higher than the
727 // penalty for a trainling "(" is a temporary workaround until we can
728 // properly avoid breaking in array subscripts or template parameters.
729 if (Left.is(tok::l_square) || Left.Type == TT_TemplateOpener)
730 return 50;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000731
Daniel Jasper399d24b2013-01-09 07:06:56 +0000732 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
733 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000734 prec::Level Level = getPrecedence(Left);
735
Daniel Jasperde5c2072012-12-24 00:13:23 +0000736 if (Level != prec::Unknown)
737 return Level;
738
Daniel Jasper04468962013-01-18 10:56:38 +0000739 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +0000740 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasper04468962013-01-18 10:56:38 +0000741 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000742 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000743 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000744
Daniel Jasperf7935112012-12-03 18:12:45 +0000745 return 3;
746 }
747
Daniel Jasper2df93312013-01-09 10:16:05 +0000748 unsigned getColumnLimit() {
749 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
750 }
751
Daniel Jasperf7935112012-12-03 18:12:45 +0000752 /// \brief Calculate the number of lines needed to format the remaining part
753 /// of the unwrapped line.
754 ///
755 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000756 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000757 /// added after the previous token.
758 ///
759 /// \param StopAt is used for optimization. If we can determine that we'll
760 /// definitely need at least \p StopAt additional lines, we already know of a
761 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000762 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000763 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000764 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000765 return 0;
766
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000767 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000768 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000769 if (NewLine && !State.NextToken->CanBreakBefore &&
770 !(State.NextToken->is(tok::r_brace) &&
771 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000772 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000773 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000774 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000775 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000776 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000777 State.LineContainsContinuedForLoopSection)
778 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000779 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000780 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000781 State.Stack.back().BreakAfterComma)
782 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000783 // Trying to insert a parameter on a new line if there are already more than
784 // one parameter on the current line is bin packing.
785 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
786 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
787 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000788 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
789 (State.NextToken->Parent->ClosesTemplateDeclaration &&
790 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000791 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000792
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000793 unsigned CurrentPenalty = 0;
794 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000795 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000796 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000797 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000798 if (State.Stack.size() < State.StartOfLineLevel &&
799 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000800 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000801 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000802 }
803
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000804 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000805
Daniel Jasper2df93312013-01-09 10:16:05 +0000806 // Exceeding column limit is bad, assign penalty.
807 if (State.Column > getColumnLimit()) {
808 unsigned ExcessCharacters = State.Column - getColumnLimit();
809 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
810 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000811
Daniel Jasperf7935112012-12-03 18:12:45 +0000812 if (StopAt <= CurrentPenalty)
813 return UINT_MAX;
814 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000815 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000816 if (I != Memory.end()) {
817 // If this state has already been examined, we can safely return the
818 // previous result if we
819 // - have not hit the optimatization (and thus returned UINT_MAX) OR
820 // - are now computing for a smaller or equal StopAt.
821 unsigned SavedResult = I->second.first;
822 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000823 if (SavedResult != UINT_MAX)
824 return SavedResult + CurrentPenalty;
825 else if (StopAt <= SavedStopAt)
826 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000827 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000828
829 unsigned NoBreak = calcPenalty(State, false, StopAt);
830 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
831 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000832
833 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
834 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000835 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000836
837 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000838 }
839
Daniel Jasperf7935112012-12-03 18:12:45 +0000840 FormatStyle Style;
841 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000842 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000843 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000844 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000845 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000846
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000847 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000848 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000849 StateMap Memory;
850
Daniel Jasperf7935112012-12-03 18:12:45 +0000851 OptimizationParameters Parameters;
852};
853
854/// \brief Determines extra information about the tokens comprising an
855/// \c UnwrappedLine.
856class TokenAnnotator {
857public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000858 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
859 AnnotatedLine &Line)
860 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000861
862 /// \brief A parser that gathers additional information about tokens.
863 ///
864 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
865 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
866 /// into template parameter lists.
867 class AnnotatingParser {
868 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000869 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000870 : CurrentToken(&RootToken), KeywordVirtualFound(false),
871 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000872
Nico Weber250fe712013-01-18 02:43:57 +0000873 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
874 struct ObjCSelectorRAII {
875 AnnotatingParser &P;
876 bool ColonWasObjCMethodExpr;
877
878 ObjCSelectorRAII(AnnotatingParser &P)
879 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
880
881 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
882
883 void markStart(AnnotatedToken &Left) {
884 P.ColonIsObjCMethodExpr = true;
885 Left.Type = TT_ObjCMethodExpr;
886 }
887
888 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
889 };
890
891
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000892 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000893 if (CurrentToken == NULL)
894 return false;
895 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000896 while (CurrentToken != NULL) {
897 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000898 Left->MatchingParen = CurrentToken;
899 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000900 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000901 next();
902 return true;
903 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000904 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
905 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000906 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000907 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
908 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000909 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000910 if (CurrentToken->is(tok::comma))
911 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000912 if (!consumeToken())
913 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000914 }
915 return false;
916 }
917
Nico Weber80a82762013-01-17 17:17:19 +0000918 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000919 if (CurrentToken == NULL)
920 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000921 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000922 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000923 if (CurrentToken->is(tok::caret)) {
924 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000925 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000926 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
927 // @selector( starts a selector.
928 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
929 MaybeSel->Parent->is(tok::at)) {
930 StartsObjCMethodExpr = true;
931 }
932 }
933
934 ObjCSelectorRAII objCSelector(*this);
935 if (StartsObjCMethodExpr)
936 objCSelector.markStart(*Left);
937
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000938 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000939 // LookForDecls is set when "if (" has been seen. Check for
940 // 'identifier' '*' 'identifier' followed by not '=' -- this
941 // '*' has to be a binary operator but determineStarAmpUsage() will
942 // categorize it as an unary operator, so set the right type here.
943 if (LookForDecls && !CurrentToken->Children.empty()) {
944 AnnotatedToken &Prev = *CurrentToken->Parent;
945 AnnotatedToken &Next = CurrentToken->Children[0];
946 if (Prev.Parent->is(tok::identifier) &&
947 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
948 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
949 Prev.Type = TT_BinaryOperator;
950 LookForDecls = false;
951 }
952 }
953
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000954 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000955 Left->MatchingParen = CurrentToken;
956 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000957
958 if (StartsObjCMethodExpr)
959 objCSelector.markEnd(*CurrentToken);
960
Daniel Jasperf7935112012-12-03 18:12:45 +0000961 next();
962 return true;
963 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000964 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +0000966 if (CurrentToken->is(tok::comma))
967 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000968 if (!consumeToken())
969 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000970 }
971 return false;
972 }
973
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000974 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000975 if (!CurrentToken)
976 return false;
977
978 // A '[' could be an index subscript (after an indentifier or after
979 // ')' or ']'), or it could be the start of an Objective-C method
980 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000981 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000982 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000983 !Left->Parent || Left->Parent->is(tok::colon) ||
984 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
985 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
986 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000987 true, true) > prec::Unknown;
988
Nico Weber250fe712013-01-18 02:43:57 +0000989 ObjCSelectorRAII objCSelector(*this);
990 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000991 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000992
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000993 while (CurrentToken != NULL) {
994 if (CurrentToken->is(tok::r_square)) {
Daniel Jasper0b820602013-01-22 11:46:26 +0000995 if (!CurrentToken->Children.empty() &&
996 CurrentToken->Children[0].is(tok::l_paren)) {
997 // An ObjC method call can't be followed by an open parenthesis.
998 // FIXME: Do we incorrectly label ":" with this?
999 StartsObjCMethodExpr = false;
1000 Left->Type = TT_Unknown;
1001 }
Nico Weber250fe712013-01-18 02:43:57 +00001002 if (StartsObjCMethodExpr)
1003 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +00001004 Left->MatchingParen = CurrentToken;
1005 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +00001006 next();
1007 return true;
1008 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001009 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +00001010 return false;
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001011 if (CurrentToken->is(tok::comma))
1012 ++Left->ParameterCount;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001013 if (!consumeToken())
1014 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001015 }
1016 return false;
1017 }
1018
Daniel Jasper83a54d22013-01-10 09:26:47 +00001019 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001020 // Lines are fine to end with '{'.
1021 if (CurrentToken == NULL)
1022 return true;
1023 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001024 while (CurrentToken != NULL) {
1025 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +00001026 Left->MatchingParen = CurrentToken;
1027 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001028 next();
1029 return true;
1030 }
1031 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
1032 return false;
1033 if (!consumeToken())
1034 return false;
1035 }
Daniel Jasper83a54d22013-01-10 09:26:47 +00001036 return true;
1037 }
1038
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001039 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001040 while (CurrentToken != NULL) {
1041 if (CurrentToken->is(tok::colon)) {
1042 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001043 next();
1044 return true;
1045 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001046 if (!consumeToken())
1047 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001048 }
1049 return false;
1050 }
1051
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001052 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001053 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1054 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001055 next();
1056 if (!parseAngle())
1057 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001058 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001059 return true;
1060 }
1061 return false;
1062 }
1063
Daniel Jasperc0880a92013-01-04 18:52:56 +00001064 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001065 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001067 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001068 case tok::plus:
1069 case tok::minus:
1070 // At the start of the line, +/- specific ObjectiveC method
1071 // declarations.
1072 if (Tok->Parent == NULL)
1073 Tok->Type = TT_ObjCMethodSpecifier;
1074 break;
Nico Webera7252d82013-01-12 06:18:40 +00001075 case tok::colon:
1076 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001077 if (Tok->Parent->is(tok::r_paren))
1078 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001079 if (ColonIsObjCMethodExpr)
1080 Tok->Type = TT_ObjCMethodExpr;
1081 break;
Nico Weber80a82762013-01-17 17:17:19 +00001082 case tok::kw_if:
1083 case tok::kw_while:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001084 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber80a82762013-01-17 17:17:19 +00001085 next();
1086 if (!parseParens(/*LookForDecls=*/true))
1087 return false;
1088 }
1089 break;
Nico Webera5510af2013-01-18 05:50:57 +00001090 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001091 if (!parseParens())
1092 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001093 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001094 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001095 if (!parseSquare())
1096 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001097 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001098 case tok::l_brace:
1099 if (!parseBrace())
1100 return false;
1101 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001102 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001103 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001104 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001105 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001106 Tok->Type = TT_BinaryOperator;
1107 CurrentToken = Tok;
1108 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001109 }
1110 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001111 case tok::r_paren:
1112 case tok::r_square:
1113 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001114 case tok::r_brace:
1115 // Lines can start with '}'.
1116 if (Tok->Parent != NULL)
1117 return false;
1118 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001119 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001120 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001121 break;
1122 case tok::kw_operator:
Manuel Klimekd33516e2013-01-23 10:09:28 +00001123 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001124 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001125 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001126 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1127 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001128 next();
1129 }
1130 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001131 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1132 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001133 next();
1134 }
1135 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001136 break;
1137 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001138 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001139 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001140 case tok::kw_template:
1141 parseTemplateDeclaration();
1142 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001143 default:
1144 break;
1145 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001146 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001147 }
1148
Daniel Jasper050948a52012-12-21 17:58:39 +00001149 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001150 next();
1151 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1152 next();
1153 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001154 if (CurrentToken->isNot(tok::comment) ||
1155 !CurrentToken->Children.empty())
1156 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001157 next();
1158 }
1159 } else {
1160 while (CurrentToken != NULL) {
1161 next();
1162 }
1163 }
1164 }
1165
1166 void parseWarningOrError() {
1167 next();
1168 // We still want to format the whitespace left of the first token of the
1169 // warning or error.
1170 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001171 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001172 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001173 next();
1174 }
1175 }
1176
1177 void parsePreprocessorDirective() {
1178 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001179 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001180 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001181 // Hashes in the middle of a line can lead to any strange token
1182 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001183 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001184 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001185 switch (
1186 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001187 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001188 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001189 parseIncludeDirective();
1190 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001191 case tok::pp_error:
1192 case tok::pp_warning:
1193 parseWarningOrError();
1194 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001195 default:
1196 break;
1197 }
1198 }
1199
Daniel Jasperda16db32013-01-07 10:48:50 +00001200 LineType parseLine() {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001201 int PeriodsAndArrows = 0;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001202 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001203 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001204 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001205 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001206 while (CurrentToken != NULL) {
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001207
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001208 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001209 KeywordVirtualFound = true;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001210 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1211 ++PeriodsAndArrows;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001212 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001213 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001214 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001215 if (KeywordVirtualFound)
1216 return LT_VirtualFunctionDecl;
Daniel Jasper50e7ab72013-01-22 14:28:24 +00001217
1218 // Assume a builder-type call if there are 2 or more "." and "->".
1219 if (PeriodsAndArrows >= 2)
1220 return LT_BuilderTypeCall;
1221
Daniel Jasperda16db32013-01-07 10:48:50 +00001222 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001223 }
1224
1225 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001226 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1227 CurrentToken = &CurrentToken->Children[0];
1228 else
1229 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001230 }
1231
1232 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001233 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001234 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001235 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001236 };
1237
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001238 void calculateExtraInformation(AnnotatedToken &Current) {
1239 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1240
Manuel Klimek52b15152013-01-09 15:25:02 +00001241 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001242 Current.MustBreakBefore = true;
1243 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001244 if (Current.Type == TT_LineComment) {
1245 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001246 } else if ((Current.Parent->is(tok::comment) &&
1247 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001248 (Current.is(tok::string_literal) &&
1249 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001250 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001251 } else {
1252 Current.MustBreakBefore = false;
1253 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001254 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001255 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001256 if (Current.MustBreakBefore)
1257 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1258 else
1259 Current.TotalLength = Current.Parent->TotalLength +
1260 Current.FormatTok.TokenLength +
1261 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001262 if (!Current.Children.empty())
1263 calculateExtraInformation(Current.Children[0]);
1264 }
1265
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001266 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001267 AnnotatingParser Parser(Line.First);
1268 Line.Type = Parser.parseLine();
1269 if (Line.Type == LT_Invalid)
1270 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001271
Daniel Jasper5b49f472013-01-23 12:10:53 +00001272 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001273
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001274 if (Line.First.Type == TT_ObjCMethodSpecifier)
1275 Line.Type = LT_ObjCMethodDecl;
1276 else if (Line.First.Type == TT_ObjCDecl)
1277 Line.Type = LT_ObjCDecl;
1278 else if (Line.First.Type == TT_ObjCProperty)
1279 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001280
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001281 Line.First.SpaceRequiredBefore = true;
1282 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1283 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001284
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001285 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001286 if (!Line.First.Children.empty())
1287 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001288 }
1289
1290private:
Daniel Jasper5b49f472013-01-23 12:10:53 +00001291 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1292 if (getPrecedence(Current) == prec::Assignment) {
1293 IsExpression = true;
1294 AnnotatedToken *Previous = Current.Parent;
1295 while (Previous != NULL) {
Manuel Klimekc1237a82013-01-23 14:08:21 +00001296 if (Previous->Type == TT_BinaryOperator &&
1297 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001298 Previous->Type = TT_PointerOrReference;
Manuel Klimekc1237a82013-01-23 14:08:21 +00001299 }
Daniel Jasper5b49f472013-01-23 12:10:53 +00001300 Previous = Previous->Parent;
1301 }
1302 }
1303 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper420d7d32013-01-23 12:58:14 +00001304 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1305 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper5b49f472013-01-23 12:10:53 +00001306 IsExpression = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001307
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001308 if (Current.Type == TT_Unknown) {
1309 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper5b49f472013-01-23 12:10:53 +00001310 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001311 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1312 Current.is(tok::caret)) {
1313 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001314 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1315 Current.Type = determineIncrementUsage(Current);
1316 } else if (Current.is(tok::exclaim)) {
1317 Current.Type = TT_UnaryOperator;
1318 } else if (isBinaryOperator(Current)) {
1319 Current.Type = TT_BinaryOperator;
1320 } else if (Current.is(tok::comment)) {
1321 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1322 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001323 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001324 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001325 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001326 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001327 } else if (Current.is(tok::r_paren) &&
1328 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001329 Current.Parent->Type == TT_TemplateCloser) &&
1330 (Current.Children.empty() ||
1331 (Current.Children[0].isNot(tok::equal) &&
1332 Current.Children[0].isNot(tok::semi) &&
1333 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001334 // FIXME: We need to get smarter and understand more cases of casts.
1335 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001336 } else if (Current.is(tok::at) && Current.Children.size()) {
1337 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1338 case tok::objc_interface:
1339 case tok::objc_implementation:
1340 case tok::objc_protocol:
1341 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001342 break;
1343 case tok::objc_property:
1344 Current.Type = TT_ObjCProperty;
1345 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001346 default:
1347 break;
1348 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001349 }
1350 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001351
1352 if (!Current.Children.empty())
Daniel Jasper5b49f472013-01-23 12:10:53 +00001353 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperf7935112012-12-03 18:12:45 +00001354 }
1355
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001356 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001357 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001358 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001359 }
1360
Daniel Jasper71945272013-01-15 14:27:39 +00001361 /// \brief Returns the previous token ignoring comments.
1362 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1363 const AnnotatedToken *PrevToken = Tok.Parent;
1364 while (PrevToken != NULL && PrevToken->is(tok::comment))
1365 PrevToken = PrevToken->Parent;
1366 return PrevToken;
1367 }
1368
1369 /// \brief Returns the next token ignoring comments.
1370 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1371 if (Tok.Children.empty())
1372 return NULL;
1373 const AnnotatedToken *NextToken = &Tok.Children[0];
1374 while (NextToken->is(tok::comment)) {
1375 if (NextToken->Children.empty())
1376 return NULL;
1377 NextToken = &NextToken->Children[0];
1378 }
1379 return NextToken;
1380 }
1381
1382 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001383 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1384 bool IsExpression) {
Daniel Jasper71945272013-01-15 14:27:39 +00001385 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1386 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001387 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001388
1389 const AnnotatedToken *NextToken = getNextToken(Tok);
1390 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001391 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001392
Daniel Jasper0b820602013-01-22 11:46:26 +00001393 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1394 return TT_PointerOrReference;
1395
Daniel Jasper71945272013-01-15 14:27:39 +00001396 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1397 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1398 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1399 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001400 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001401 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001402
Daniel Jasper71945272013-01-15 14:27:39 +00001403 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1404 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1405 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1406 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1407 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1408 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1409 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001410 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001411
Daniel Jasper71945272013-01-15 14:27:39 +00001412 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1413 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001414 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001415
Daniel Jasper426702d2012-12-05 07:51:39 +00001416 // It is very unlikely that we are going to find a pointer or reference type
1417 // definition on the RHS of an assignment.
Daniel Jasper5b49f472013-01-23 12:10:53 +00001418 if (IsExpression)
Daniel Jasperda16db32013-01-07 10:48:50 +00001419 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001420
Daniel Jasperda16db32013-01-07 10:48:50 +00001421 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001422 }
1423
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001424 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001425 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1426 if (PrevToken == NULL)
1427 return TT_UnaryOperator;
1428
Daniel Jasper8dd40472012-12-21 09:41:31 +00001429 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001430 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1431 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1432 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1433 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1434 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001435 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001436
1437 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001438 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001439 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001440
1441 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001442 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001443 }
1444
1445 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001446 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001447 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1448 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001449 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001450 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1451 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001452 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001453
Daniel Jasperda16db32013-01-07 10:48:50 +00001454 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001455 }
1456
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001457 bool spaceRequiredBetween(const AnnotatedToken &Left,
1458 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001459 if (Right.is(tok::hashhash))
1460 return Left.is(tok::hash);
1461 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1462 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001463 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1464 return false;
Nico Webera6087752013-01-10 20:12:55 +00001465 if (Right.is(tok::less) &&
1466 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001467 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001468 return true;
1469 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1470 return false;
1471 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1472 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001473 if (Left.is(tok::at) &&
1474 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1475 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001476 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1477 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001478 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001479 if (Left.is(tok::coloncolon))
1480 return false;
1481 if (Right.is(tok::coloncolon))
1482 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001483 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1484 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001485 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001486 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001487 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1488 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001489 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001490 return Right.FormatTok.Tok.isLiteral() ||
1491 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001492 if (Right.is(tok::star) && Left.is(tok::l_paren))
1493 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001494 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1495 return false;
1496 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001497 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001498 if (Left.is(tok::period) || Right.is(tok::period))
1499 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001500 if (Left.is(tok::colon))
1501 return Left.Type != TT_ObjCMethodExpr;
1502 if (Right.is(tok::colon))
1503 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001504 if (Left.is(tok::l_paren))
1505 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001506 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001507 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001508 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001509 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001510 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1511 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001512 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001513 if (Left.is(tok::at) &&
1514 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001515 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001516 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1517 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001518 return true;
1519 }
1520
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001521 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001522 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001523 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1524 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001525 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001526 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001527 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001528 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001529 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001530 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001531 // Don't space between ')' and <id>
1532 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001533 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001534 // Don't space between ':' and '('
1535 return false;
1536 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001537 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001538 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1539 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001540
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001541 if (Tok.Parent->is(tok::comma))
1542 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001543 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001544 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001545 if (Tok.Type == TT_OverloadedOperator)
1546 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001547 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001548 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001549 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001550 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001551 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001552 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001553 if (Tok.Parent->Type == TT_UnaryOperator ||
1554 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001555 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001556 if (Tok.Type == TT_UnaryOperator)
1557 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001558 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1559 (Tok.Parent->isNot(tok::colon) ||
1560 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001561 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1562 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001563 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1564 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001565 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001566 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001567 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001568 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001569 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001570 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001571 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001572 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001573 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001574 }
1575
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001576 bool canBreakBefore(const AnnotatedToken &Right) {
1577 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001578 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001579 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1580 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001581 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001582 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1583 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001584 // Don't break this identifier as ':' or identifier
1585 // before it will break.
1586 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001587 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1588 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001589 // Don't break at ':' if identifier before it can beak.
1590 return false;
1591 }
Nico Webera7252d82013-01-12 06:18:40 +00001592 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1593 return false;
1594 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1595 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001596 if (isObjCSelectorName(Right))
1597 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001598 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001599 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001600 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001601 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001602 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001603 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001604 return false;
1605
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001606 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001607 // We rely on MustBreakBefore being set correctly here as we should not
1608 // change the "binding" behavior of a comment.
1609 return false;
1610
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001611 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1612 // unless it is follow by ';', '{' or '='.
1613 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1614 Left.Parent->is(tok::r_paren))
1615 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1616 Right.isNot(tok::equal);
1617
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001618 // We only break before r_brace if there was a corresponding break before
1619 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1620 if (Right.is(tok::r_brace))
1621 return false;
1622
Daniel Jasper71945272013-01-15 14:27:39 +00001623 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001624 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001625 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1626 Left.is(tok::comma) || Right.is(tok::lessless) ||
1627 Right.is(tok::arrow) || Right.is(tok::period) ||
Daniel Jasper45797022013-01-25 10:57:27 +00001628 Right.is(tok::colon) || Left.is(tok::coloncolon) ||
1629 Left.is(tok::semi) || Left.is(tok::l_brace) ||
1630 Left.is(tok::question) || Left.Type == TT_ConditionalExpr ||
1631 (Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
1632 Right.is(tok::identifier)) ||
Daniel Jasper7b5773e92013-01-28 07:35:34 +00001633 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
1634 (Left.is(tok::l_square) && !Right.is(tok::r_square));
Daniel Jasperf7935112012-12-03 18:12:45 +00001635 }
1636
Daniel Jasperf7935112012-12-03 18:12:45 +00001637 FormatStyle Style;
1638 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001639 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001640 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001641};
1642
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001643class LexerBasedFormatTokenSource : public FormatTokenSource {
1644public:
1645 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001646 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001647 IdentTable(Lex.getLangOpts()) {
1648 Lex.SetKeepWhitespaceMode(true);
1649 }
1650
1651 virtual FormatToken getNextToken() {
1652 if (GreaterStashed) {
1653 FormatTok.NewlinesBefore = 0;
1654 FormatTok.WhiteSpaceStart =
1655 FormatTok.Tok.getLocation().getLocWithOffset(1);
1656 FormatTok.WhiteSpaceLength = 0;
1657 GreaterStashed = false;
1658 return FormatTok;
1659 }
1660
1661 FormatTok = FormatToken();
1662 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001663 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001664 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001665 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1666 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001667
1668 // Consume and record whitespace until we find a significant token.
1669 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001670 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001671 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1672 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001673 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1674
1675 if (FormatTok.Tok.is(tok::eof))
1676 return FormatTok;
1677 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001678 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001679 }
Manuel Klimekef920692013-01-07 07:56:50 +00001680
1681 // Now FormatTok is the next non-whitespace token.
1682 FormatTok.TokenLength = Text.size();
1683
Manuel Klimek1abf7892013-01-04 23:34:14 +00001684 // In case the token starts with escaped newlines, we want to
1685 // take them into account as whitespace - this pattern is quite frequent
1686 // in macro definitions.
1687 // FIXME: What do we want to do with other escaped spaces, and escaped
1688 // spaces or newlines in the middle of tokens?
1689 // FIXME: Add a more explicit test.
1690 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001691 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00001692 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimek1abf7892013-01-04 23:34:14 +00001693 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001694 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001695 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001696 }
1697
1698 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001699 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001700 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001701 FormatTok.Tok.setKind(Info.getTokenID());
1702 }
1703
1704 if (FormatTok.Tok.is(tok::greatergreater)) {
1705 FormatTok.Tok.setKind(tok::greater);
1706 GreaterStashed = true;
1707 }
1708
1709 return FormatTok;
1710 }
1711
1712private:
1713 FormatToken FormatTok;
1714 bool GreaterStashed;
1715 Lexer &Lex;
1716 SourceManager &SourceMgr;
1717 IdentifierTable IdentTable;
1718
1719 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001720 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001721 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1722 Tok.getLength());
1723 }
1724};
1725
Daniel Jasperf7935112012-12-03 18:12:45 +00001726class Formatter : public UnwrappedLineConsumer {
1727public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001728 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1729 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001730 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001731 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001732 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001733
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001734 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001735
Daniel Jasperf7935112012-12-03 18:12:45 +00001736 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001737 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001738 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001739 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001740 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001741 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1742 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1743 Annotator.annotate();
1744 }
1745 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1746 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001747 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001748 const AnnotatedLine &TheLine = *I;
1749 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1750 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1751 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001752 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001753 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001754 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001755 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001756 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001757 PreviousEndOfLineColumn = Formatter.format();
1758 } else {
1759 // If we did not reformat this unwrapped line, the column at the end of
1760 // the last token is unchanged - thus, we can calculate the end of the
1761 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001762 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001763 SourceMgr.getSpellingColumnNumber(
1764 TheLine.Last->FormatTok.Tok.getLocation()) +
1765 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1766 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001767 1;
1768 }
1769 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001770 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001771 }
1772
1773private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001774 /// \brief Tries to merge lines into one.
1775 ///
1776 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1777 /// if possible; note that \c I will be incremented when lines are merged.
1778 ///
1779 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001780 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001781 std::vector<AnnotatedLine>::iterator &I,
1782 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001783 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1784
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001785 // We can never merge stuff if there are trailing line comments.
1786 if (I->Last->Type == TT_LineComment)
1787 return;
1788
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001789 // Check whether the UnwrappedLine can be put onto a single line. If
1790 // so, this is bound to be the optimal solution (by definition) and we
1791 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001792 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001793 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001794 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001795
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001796 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001797 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001798
Daniel Jasper25837aa2013-01-14 14:14:23 +00001799 if (I->Last->is(tok::l_brace)) {
1800 tryMergeSimpleBlock(I, E, Limit);
1801 } else if (I->First.is(tok::kw_if)) {
1802 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001803 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1804 I->First.FormatTok.IsFirst)) {
1805 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001806 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001807 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001808 }
1809
Daniel Jasper39825ea2013-01-14 15:40:57 +00001810 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1811 std::vector<AnnotatedLine>::iterator E,
1812 unsigned Limit) {
1813 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001814 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1815 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001816 if (I + 2 != E && (I + 2)->InPPDirective &&
1817 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1818 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001819 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001820 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001821 join(Line, *(++I));
1822 }
1823
Daniel Jasper25837aa2013-01-14 14:14:23 +00001824 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1825 std::vector<AnnotatedLine>::iterator E,
1826 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001827 if (!Style.AllowShortIfStatementsOnASingleLine)
1828 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001829 if ((I + 1)->InPPDirective != I->InPPDirective ||
1830 ((I + 1)->InPPDirective &&
1831 (I + 1)->First.FormatTok.HasUnescapedNewline))
1832 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001833 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001834 if (Line.Last->isNot(tok::r_paren))
1835 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001836 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001837 return;
1838 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1839 return;
1840 // Only inline simple if's (no nested if or else).
1841 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1842 return;
1843 join(Line, *(++I));
1844 }
1845
1846 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1847 std::vector<AnnotatedLine>::iterator E,
1848 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001849 // First, check that the current line allows merging. This is the case if
1850 // we're not in a control flow statement and the last token is an opening
1851 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001852 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001853 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001854 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1855 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1856 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1857 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001858 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001859 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1860 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001861 if (!AllowedTokens)
1862 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001863
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001864 AnnotatedToken *Tok = &(I + 1)->First;
1865 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1866 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1867 Tok->SpaceRequiredBefore = false;
1868 join(Line, *(I + 1));
1869 I += 1;
1870 } else {
1871 // Check that we still have three lines and they fit into the limit.
1872 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1873 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001874 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001875
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001876 // Second, check that the next line does not contain any braces - if it
1877 // does, readability declines when putting it into a single line.
1878 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1879 return;
1880 do {
1881 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1882 return;
1883 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1884 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001885
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001886 // Last, check that the third line contains a single closing brace.
1887 Tok = &(I + 2)->First;
1888 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1889 Tok->MustBreakBefore)
1890 return;
1891
1892 join(Line, *(I + 1));
1893 join(Line, *(I + 2));
1894 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001895 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001896 }
1897
1898 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1899 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001900 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1901 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001902 }
1903
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001904 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1905 A.Last->Children.push_back(B.First);
1906 while (!A.Last->Children.empty()) {
1907 A.Last->Children[0].Parent = A.Last;
1908 A.Last = &A.Last->Children[0];
1909 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001910 }
1911
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001912 bool touchesRanges(const AnnotatedLine &TheLine) {
1913 const FormatToken *First = &TheLine.First.FormatTok;
1914 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001915 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001916 First->Tok.getLocation(),
1917 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001918 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001919 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1920 Ranges[i].getBegin()) &&
1921 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1922 LineRange.getBegin()))
1923 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001924 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001925 return false;
1926 }
1927
1928 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001929 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001930 }
1931
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001932 /// \brief Add a new line and the required indent before the first Token
1933 /// of the \c UnwrappedLine if there was no structural parsing error.
1934 /// Returns the indent level of the \c UnwrappedLine.
1935 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1936 bool InPPDirective,
1937 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001938 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001939 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1940 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1941
1942 unsigned Newlines = std::min(Tok.NewlinesBefore,
1943 Style.MaxEmptyLinesToKeep + 1);
1944 if (Newlines == 0 && !Tok.IsFirst)
1945 Newlines = 1;
1946 unsigned Indent = Level * 2;
1947
1948 bool IsAccessModifier = false;
1949 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1950 RootToken.is(tok::kw_private))
1951 IsAccessModifier = true;
1952 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1953 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1954 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1955 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1956 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1957 IsAccessModifier = true;
1958
1959 if (IsAccessModifier &&
1960 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1961 Indent += Style.AccessModifierOffset;
1962 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001963 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001964 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001965 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1966 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001967 }
1968 return Indent;
1969 }
1970
Alexander Kornienko116ba682013-01-14 11:34:14 +00001971 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001972 FormatStyle Style;
1973 Lexer &Lex;
1974 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001975 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001976 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001977 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001978 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001979};
1980
1981tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1982 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001983 std::vector<CharSourceRange> Ranges,
1984 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001985 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001986 OwningPtr<DiagnosticConsumer> DiagPrinter;
1987 if (DiagClient == 0) {
1988 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1989 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1990 DiagClient = DiagPrinter.get();
1991 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001992 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001993 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001994 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001995 Diagnostics.setSourceManager(&SourceMgr);
1996 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001997 return formatter.format();
1998}
1999
Daniel Jasperc1fa2812013-01-10 13:08:12 +00002000LangOptions getFormattingLangOpts() {
2001 LangOptions LangOpts;
2002 LangOpts.CPlusPlus = 1;
2003 LangOpts.CPlusPlus11 = 1;
2004 LangOpts.Bool = 1;
2005 LangOpts.ObjC1 = 1;
2006 LangOpts.ObjC2 = 1;
2007 return LangOpts;
2008}
2009
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002010} // namespace format
2011} // namespace clang