blob: 2952067c398db5eb714fe83cc7588dcd8ddbf819 [file] [log] [blame]
Daniel Jasperbac016b2012-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 Klimekca547db2013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasper675d2e32012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruthb99083e2013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko3048aea2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperbac016b2012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimekca547db2013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8822d3a2012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimekca547db2013-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 Jasperbac016b2012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasper71607512013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasper71607512013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasper71607512013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek407a31a2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasper46ef8522013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Webered91bba2013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Weberbcfdd262013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Weber70848232013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasper71607512013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper5cf7cf32013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasper71607512013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
Daniel Jasper32983272013-01-22 14:28:24 +000063 LT_BuilderTypeCall,
Daniel Jasper71607512013-01-07 10:48:50 +000064 LT_PreprocessorDirective,
65 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000066 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000067 LT_ObjCMethodDecl,
68 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000069};
70
Daniel Jasper26f7e782013-01-08 14:56:18 +000071class AnnotatedToken {
72public:
Daniel Jasperdcc2a622013-01-18 08:44:07 +000073 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000074 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
75 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper0df6acd2013-01-16 14:59:02 +000076 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000077
Daniel Jasperfeb18f52013-01-14 14:14:23 +000078 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
79 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
80
Daniel Jasper26f7e782013-01-08 14:56:18 +000081 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
82 return FormatTok.Tok.isObjCAtKeyword(Kind);
83 }
84
85 FormatToken FormatTok;
86
Daniel Jasperbac016b2012-12-03 18:12:45 +000087 TokenType Type;
88
Daniel Jasperbac016b2012-12-03 18:12:45 +000089 bool SpaceRequiredBefore;
90 bool CanBreakBefore;
91 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000092
93 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000094
Daniel Jasper0df6acd2013-01-16 14:59:02 +000095 AnnotatedToken *MatchingParen;
96
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +000097 /// \brief The total length of the line up to and including this token.
98 unsigned TotalLength;
99
Daniel Jasper26f7e782013-01-08 14:56:18 +0000100 std::vector<AnnotatedToken> Children;
101 AnnotatedToken *Parent;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000102
103 const AnnotatedToken *getPreviousNoneComment() const {
104 AnnotatedToken *Tok = Parent;
105 while (Tok != NULL && Tok->is(tok::comment))
106 Tok = Tok->Parent;
107 return Tok;
108 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000109};
110
Daniel Jasper995e8202013-01-14 13:08:07 +0000111class AnnotatedLine {
112public:
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000113 AnnotatedLine(const UnwrappedLine &Line)
114 : First(Line.Tokens.front()), Level(Line.Level),
Manuel Klimek70b03f42013-01-23 09:32:48 +0000115 InPPDirective(Line.InPPDirective),
116 MustBeDeclaration(Line.MustBeDeclaration) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000117 assert(!Line.Tokens.empty());
118 AnnotatedToken *Current = &First;
119 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
120 E = Line.Tokens.end();
121 I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000122 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000123 Current->Children[0].Parent = Current;
124 Current = &Current->Children[0];
125 }
126 Last = Current;
127 }
128 AnnotatedLine(const AnnotatedLine &Other)
129 : First(Other.First), Type(Other.Type), Level(Other.Level),
Manuel Klimek70b03f42013-01-23 09:32:48 +0000130 InPPDirective(Other.InPPDirective),
131 MustBeDeclaration(Other.MustBeDeclaration) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000132 Last = &First;
133 while (!Last->Children.empty()) {
134 Last->Children[0].Parent = Last;
135 Last = &Last->Children[0];
136 }
137 }
138
Daniel Jasper995e8202013-01-14 13:08:07 +0000139 AnnotatedToken First;
140 AnnotatedToken *Last;
141
142 LineType Type;
143 unsigned Level;
144 bool InPPDirective;
Manuel Klimek70b03f42013-01-23 09:32:48 +0000145 bool MustBeDeclaration;
Daniel Jasper995e8202013-01-14 13:08:07 +0000146};
147
Daniel Jasper26f7e782013-01-08 14:56:18 +0000148static prec::Level getPrecedence(const AnnotatedToken &Tok) {
149 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +0000150}
151
Daniel Jasperbac016b2012-12-03 18:12:45 +0000152FormatStyle getLLVMStyle() {
153 FormatStyle LLVMStyle;
154 LLVMStyle.ColumnLimit = 80;
155 LLVMStyle.MaxEmptyLinesToKeep = 1;
156 LLVMStyle.PointerAndReferenceBindToType = false;
157 LLVMStyle.AccessModifierOffset = -2;
158 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000159 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000160 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000161 LLVMStyle.BinPackParameters = true;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000162 LLVMStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000163 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000164 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000165 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000166 return LLVMStyle;
167}
168
169FormatStyle getGoogleStyle() {
170 FormatStyle GoogleStyle;
171 GoogleStyle.ColumnLimit = 80;
172 GoogleStyle.MaxEmptyLinesToKeep = 1;
173 GoogleStyle.PointerAndReferenceBindToType = true;
174 GoogleStyle.AccessModifierOffset = -1;
175 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000176 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000177 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000178 GoogleStyle.BinPackParameters = false;
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000179 GoogleStyle.AllowAllParametersOnNextLine = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000180 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +0000181 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000182 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000183 return GoogleStyle;
184}
185
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000186FormatStyle getChromiumStyle() {
187 FormatStyle ChromiumStyle = getGoogleStyle();
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000188 ChromiumStyle.AllowAllParametersOnNextLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000189 return ChromiumStyle;
190}
191
Daniel Jasperbac016b2012-12-03 18:12:45 +0000192struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000193 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000194 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000195 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000196};
197
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000198/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000199///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000200/// This includes special handling for certain constructs, e.g. the alignment of
201/// trailing line comments.
202class WhitespaceManager {
203public:
204 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
205
206 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
207 /// each \c AnnotatedToken.
208 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
209 unsigned Spaces, unsigned WhitespaceStartColumn,
210 const FormatStyle &Style) {
Daniel Jasper821627e2013-01-21 22:49:20 +0000211 // 2+ newlines mean an empty line separating logic scopes.
212 if (NewLines >= 2)
213 alignComments();
214
215 // Align line comments if they are trailing or if they continue other
216 // trailing comments.
217 if (Tok.Type == TT_LineComment &&
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000218 (Tok.Parent != NULL || !Comments.empty())) {
219 if (Style.ColumnLimit >=
220 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
221 Comments.push_back(StoredComment());
222 Comments.back().Tok = Tok.FormatTok;
223 Comments.back().Spaces = Spaces;
224 Comments.back().NewLines = NewLines;
225 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
226 Comments.back().MaxColumn = Style.ColumnLimit -
227 Spaces - Tok.FormatTok.TokenLength;
228 return;
229 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000230 }
Daniel Jasper821627e2013-01-21 22:49:20 +0000231
232 // If this line does not have a trailing comment, align the stored comments.
233 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
234 alignComments();
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000235 storeReplacement(Tok.FormatTok,
236 std::string(NewLines, '\n') + std::string(Spaces, ' '));
237 }
238
239 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
240 /// backslashes to escape newlines inside a preprocessor directive.
241 ///
242 /// This function and \c replaceWhitespace have the same behavior if
243 /// \c Newlines == 0.
244 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
245 unsigned Spaces, unsigned WhitespaceStartColumn,
246 const FormatStyle &Style) {
247 std::string NewLineText;
248 if (NewLines > 0) {
249 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
250 WhitespaceStartColumn);
251 for (unsigned i = 0; i < NewLines; ++i) {
252 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
253 NewLineText += "\\\n";
254 Offset = 0;
255 }
256 }
257 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
258 }
259
260 /// \brief Returns all the \c Replacements created during formatting.
261 const tooling::Replacements &generateReplacements() {
262 alignComments();
263 return Replaces;
264 }
265
266private:
267 /// \brief Structure to store a comment for later layout and alignment.
268 struct StoredComment {
269 FormatToken Tok;
270 unsigned MinColumn;
271 unsigned MaxColumn;
272 unsigned NewLines;
273 unsigned Spaces;
274 };
275 SmallVector<StoredComment, 16> Comments;
276 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
277
278 /// \brief Try to align all stashed comments.
279 void alignComments() {
280 unsigned MinColumn = 0;
281 unsigned MaxColumn = UINT_MAX;
282 comment_iterator Start = Comments.begin();
283 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
284 ++I) {
285 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
286 alignComments(Start, I, MinColumn);
287 MinColumn = I->MinColumn;
288 MaxColumn = I->MaxColumn;
289 Start = I;
290 } else {
291 MinColumn = std::max(MinColumn, I->MinColumn);
292 MaxColumn = std::min(MaxColumn, I->MaxColumn);
293 }
294 }
295 alignComments(Start, Comments.end(), MinColumn);
296 Comments.clear();
297 }
298
299 /// \brief Put all the comments between \p I and \p E into \p Column.
300 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
301 while (I != E) {
302 unsigned Spaces = I->Spaces + Column - I->MinColumn;
303 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
304 std::string(Spaces, ' '));
305 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000306 }
307 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000308
309 /// \brief Stores \p Text as the replacement for the whitespace in front of
310 /// \p Tok.
311 void storeReplacement(const FormatToken &Tok, const std::string Text) {
312 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
313 Tok.WhiteSpaceLength, Text));
314 }
315
316 SourceManager &SourceMgr;
317 tooling::Replacements Replaces;
318};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000319
Nico Webere8ccc812013-01-12 22:48:47 +0000320/// \brief Returns if a token is an Objective-C selector name.
321///
Nico Weberea865632013-01-12 22:51:13 +0000322/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Webere8ccc812013-01-12 22:48:47 +0000323static bool isObjCSelectorName(const AnnotatedToken &Tok) {
324 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
325 Tok.Children[0].is(tok::colon) &&
326 Tok.Children[0].Type == TT_ObjCMethodExpr;
327}
328
Daniel Jasperbac016b2012-12-03 18:12:45 +0000329class UnwrappedLineFormatter {
330public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000331 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000332 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000333 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000334 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000335 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000336 FirstIndent(FirstIndent), RootToken(RootToken),
337 Whitespaces(Whitespaces) {
Daniel Jasperc79afda2013-01-18 10:56:38 +0000338 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000339 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000340 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000341 }
342
Manuel Klimekd4397b92013-01-04 23:34:14 +0000343 /// \brief Formats an \c UnwrappedLine.
344 ///
345 /// \returns The column after the last token in the last line of the
346 /// \c UnwrappedLine.
347 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000348 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000349 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000350 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000351 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000352 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000353 State.ForLoopVariablePos = 0;
354 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000355 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000356
Manuel Klimekca547db2013-01-16 14:55:28 +0000357 DEBUG({
358 DebugTokenState(*State.NextToken);
359 });
360
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000361 // The first token has already been indented and thus consumed.
362 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000363
364 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000365 while (State.NextToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000366 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
367 // Calculating the column is important for aligning trailing comments.
368 // FIXME: This does not seem to happen in conjunction with escaped
369 // newlines. If it does, fix!
370 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
371 State.NextToken->FormatTok.TokenLength;
372 State.NextToken = State.NextToken->Children.empty() ? NULL :
373 &State.NextToken->Children[0];
374 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000375 addTokenToState(false, false, State);
376 } else {
377 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
378 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimekca547db2013-01-16 14:55:28 +0000379 DEBUG({
380 if (Break < NoBreak)
381 llvm::errs() << "\n";
382 else
383 llvm::errs() << " ";
384 llvm::errs() << "<";
385 DebugPenalty(Break, Break < NoBreak);
386 llvm::errs() << "/";
387 DebugPenalty(NoBreak, !(Break < NoBreak));
388 llvm::errs() << "> ";
389 DebugTokenState(*State.NextToken);
390 });
Daniel Jasper1321eb52012-12-18 21:05:13 +0000391 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000392 if (State.NextToken != NULL &&
393 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
394 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000395 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000396 State.Stack.back().BreakAfterComma = true;
397 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000398 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000399 }
Manuel Klimekca547db2013-01-16 14:55:28 +0000400 DEBUG(llvm::errs() << "\n");
Manuel Klimekd4397b92013-01-04 23:34:14 +0000401 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000402 }
403
404private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000405 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
406 const Token &Tok = AnnotatedTok.FormatTok.Tok;
407 llvm::errs()
408 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
409 Tok.getLength());
410 llvm::errs();
411 }
412
413 void DebugPenalty(unsigned Penalty, bool Winner) {
414 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
415 if (Penalty == UINT_MAX)
416 llvm::errs() << "MAX";
417 else
418 llvm::errs() << Penalty;
419 llvm::errs().resetColor();
420 }
421
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000422 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000423 ParenState(unsigned Indent, unsigned LastSpace)
424 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000425 BreakBeforeClosingBrace(false), BreakAfterComma(false),
426 HasMultiParameterLine(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000427
Daniel Jasperbac016b2012-12-03 18:12:45 +0000428 /// \brief The position to which a specific parenthesis level needs to be
429 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000430 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000431
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000432 /// \brief The position of the last space on each level.
433 ///
434 /// Used e.g. to break like:
435 /// functionCall(Parameter, otherCall(
436 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000437 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000438
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000439 /// \brief The position the first "<<" operator encountered on each level.
440 ///
441 /// Used to align "<<" operators. 0 if no such operator has been encountered
442 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000443 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000444
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000445 /// \brief Whether a newline needs to be inserted before the block's closing
446 /// brace.
447 ///
448 /// We only want to insert a newline before the closing brace if there also
449 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000450 bool BreakBeforeClosingBrace;
451
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000452 bool BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000453 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000454
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000455 bool operator<(const ParenState &Other) const {
456 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000457 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000458 if (LastSpace != Other.LastSpace)
459 return LastSpace < Other.LastSpace;
460 if (FirstLessLess != Other.FirstLessLess)
461 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000462 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
463 return BreakBeforeClosingBrace;
Daniel Jasperb3123142013-01-12 07:36:22 +0000464 if (BreakAfterComma != Other.BreakAfterComma)
465 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000466 if (HasMultiParameterLine != Other.HasMultiParameterLine)
467 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000468 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000469 }
470 };
471
472 /// \brief The current state when indenting a unwrapped line.
473 ///
474 /// As the indenting tries different combinations this is copied by value.
475 struct LineState {
476 /// \brief The number of used columns in the current line.
477 unsigned Column;
478
479 /// \brief The token that needs to be next formatted.
480 const AnnotatedToken *NextToken;
481
482 /// \brief The parenthesis level of the first token on the current line.
483 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000484
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000485 /// \brief The column of the first variable in a for-loop declaration.
486 ///
487 /// Used to align the second variable if necessary.
488 unsigned ForLoopVariablePos;
489
490 /// \brief \c true if this line contains a continued for-loop section.
491 bool LineContainsContinuedForLoopSection;
492
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000493 /// \brief A stack keeping track of properties applying to parenthesis
494 /// levels.
495 std::vector<ParenState> Stack;
496
497 /// \brief Comparison operator to be able to used \c LineState in \c map.
498 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000499 if (Other.NextToken != NextToken)
500 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000501 if (Other.Column != Column)
502 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000503 if (Other.StartOfLineLevel != StartOfLineLevel)
504 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000505 if (Other.ForLoopVariablePos != ForLoopVariablePos)
506 return Other.ForLoopVariablePos < ForLoopVariablePos;
507 if (Other.LineContainsContinuedForLoopSection !=
508 LineContainsContinuedForLoopSection)
509 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000510 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000511 }
512 };
513
Daniel Jasper20409152012-12-04 14:54:30 +0000514 /// \brief Appends the next token to \p State and updates information
515 /// necessary for indentation.
516 ///
517 /// Puts the token on the current line if \p Newline is \c true and adds a
518 /// line break and necessary indentation otherwise.
519 ///
520 /// If \p DryRun is \c false, also creates and stores the required
521 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000522 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000523 const AnnotatedToken &Current = *State.NextToken;
524 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000525 assert(State.Stack.size());
526 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000527
528 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000529 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000530 if (Current.is(tok::r_brace)) {
531 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000532 } else if (Current.is(tok::string_literal) &&
533 Previous.is(tok::string_literal)) {
534 State.Column = State.Column - Previous.FormatTok.TokenLength;
535 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000536 State.Stack[ParenLevel].FirstLessLess != 0) {
537 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000538 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000539 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
540 Current.is(tok::period) || Previous.is(tok::question) ||
541 Previous.Type == TT_ConditionalExpr)) {
542 // Indent and extra 4 spaces after if we know the current expression is
543 // continued. Don't do that on the top level, as we already indent 4
544 // there.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000545 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000546 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000547 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000548 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000549 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000550 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000551 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000552 }
553
Manuel Klimek2851c162013-01-10 14:36:46 +0000554 // A line starting with a closing brace is assumed to be correct for the
555 // same level as before the opening brace.
556 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000557
Daniel Jasper26f7e782013-01-08 14:56:18 +0000558 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000559 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000560
Manuel Klimek060143e2013-01-02 18:33:23 +0000561 if (!DryRun) {
562 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000563 Whitespaces.replaceWhitespace(Current, 1, State.Column,
564 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000565 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000566 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
567 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000568 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000569
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000570 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Weberf681fa82013-01-12 07:05:25 +0000571 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000572 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000573 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000574 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
575 State.ForLoopVariablePos = State.Column -
576 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000577
Daniel Jasper26f7e782013-01-08 14:56:18 +0000578 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
579 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000580 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000581
Daniel Jasperbac016b2012-12-03 18:12:45 +0000582 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000583 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000584
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000585 // FIXME: Do we need to do this for assignments nested in other
586 // expressions?
587 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000588 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000589 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000590 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000591 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000592 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000593 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Manuel Klimek86721d22013-01-22 16:31:55 +0000594 if (Current.getPreviousNoneComment() != NULL &&
595 Current.getPreviousNoneComment()->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000596 Current.isNot(tok::comment))
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000597 State.Stack[ParenLevel].HasMultiParameterLine = true;
598
Daniel Jasper1321eb52012-12-18 21:05:13 +0000599
Daniel Jasper9cda8002013-01-07 13:08:40 +0000600 // Top-level spaces that are not part of assignments are exempt as that
601 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000602 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000603 if (Spaces > 0 &&
604 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000605 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000606 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000607
608 // If we break after an {, we should also break before the corresponding }.
609 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000610 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000611
Daniel Jasper8f4bd7a2013-01-23 10:08:28 +0000612 if (!Style.BinPackParameters && Newline) {
613 // If we are breaking after '(', '{', '<', this is not bin packing unless
614 // AllowAllParametersOnNextLine is false.
615 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace) &&
616 Previous.Type != TT_TemplateOpener) ||
617 !Style.AllowAllParametersOnNextLine)
618 State.Stack.back().BreakAfterComma = true;
619
620 // Any break on this level means that the parent level has been broken
621 // and we need to avoid bin packing there.
622 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
623 State.Stack[i].BreakAfterComma = true;
624 }
625 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000626
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000627 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000628 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000629
Daniel Jasper20409152012-12-04 14:54:30 +0000630 /// \brief Mark the next token as consumed in \p State and modify its stacks
631 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000632 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000633 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000634 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000635
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000636 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
637 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000638
Daniel Jaspercf225b62012-12-24 13:43:52 +0000639 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000640 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000641 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
642 Current.is(tok::l_brace) ||
643 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000644 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000645 if (Current.is(tok::l_brace)) {
646 // FIXME: This does not work with nested static initializers.
647 // Implement a better handling for static initializers and similar
648 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000649 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000650 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000651 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000652 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000653 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000654 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper20409152012-12-04 14:54:30 +0000655 }
656
Daniel Jaspercf225b62012-12-24 13:43:52 +0000657 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000658 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000659 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
660 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
661 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000662 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000663 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000664
Daniel Jasper26f7e782013-01-08 14:56:18 +0000665 if (State.NextToken->Children.empty())
666 State.NextToken = NULL;
667 else
668 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000669
670 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000671 }
672
Nico Weberdecf7bc2013-01-07 15:15:29 +0000673 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000674 unsigned splitPenalty(const AnnotatedToken &Tok) {
675 const AnnotatedToken &Left = Tok;
676 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000677
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000678 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
679 return 50;
680 if (Left.is(tok::equal) && Right.is(tok::l_brace))
681 return 150;
682
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000683 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000684 if (RootToken.is(tok::kw_for) &&
685 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000686 return 20;
687
Daniel Jasperc79afda2013-01-18 10:56:38 +0000688 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000689 return 0;
Nico Webere8ccc812013-01-12 22:48:47 +0000690
691 // In Objective-C method expressions, prefer breaking before "param:" over
692 // breaking after it.
693 if (isObjCSelectorName(Right))
694 return 0;
695 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
696 return 20;
697
Daniel Jasper26f7e782013-01-08 14:56:18 +0000698 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000699 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000700
Daniel Jasper9c837d02013-01-09 07:06:56 +0000701 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
702 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000703 prec::Level Level = getPrecedence(Left);
704
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000705 if (Level != prec::Unknown)
706 return Level;
707
Daniel Jasperc79afda2013-01-18 10:56:38 +0000708 if (Right.is(tok::arrow) || Right.is(tok::period)) {
Daniel Jasper32983272013-01-22 14:28:24 +0000709 if (Left.is(tok::r_paren) && Line.Type == LT_BuilderTypeCall)
Daniel Jasperc79afda2013-01-18 10:56:38 +0000710 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasper46a46a22013-01-07 07:13:20 +0000711 return 150;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000712 }
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000713
Daniel Jasperbac016b2012-12-03 18:12:45 +0000714 return 3;
715 }
716
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000717 unsigned getColumnLimit() {
718 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
719 }
720
Daniel Jasperbac016b2012-12-03 18:12:45 +0000721 /// \brief Calculate the number of lines needed to format the remaining part
722 /// of the unwrapped line.
723 ///
724 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000725 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 /// added after the previous token.
727 ///
728 /// \param StopAt is used for optimization. If we can determine that we'll
729 /// definitely need at least \p StopAt additional lines, we already know of a
730 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000731 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000732 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000733 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000734 return 0;
735
Daniel Jasper26f7e782013-01-08 14:56:18 +0000736 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000737 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000738 if (NewLine && !State.NextToken->CanBreakBefore &&
739 !(State.NextToken->is(tok::r_brace) &&
740 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000741 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000742 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000743 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000744 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000745 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000746 State.LineContainsContinuedForLoopSection)
747 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000748 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000749 State.NextToken->isNot(tok::comment) &&
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000750 State.Stack.back().BreakAfterComma)
751 return UINT_MAX;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000752 // Trying to insert a parameter on a new line if there are already more than
753 // one parameter on the current line is bin packing.
754 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
755 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
756 return UINT_MAX;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000757 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
758 (State.NextToken->Parent->ClosesTemplateDeclaration &&
759 State.Stack.size() == 1)))
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000760 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000761
Daniel Jasper33182dd2012-12-05 14:57:28 +0000762 unsigned CurrentPenalty = 0;
763 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000764 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000765 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000766 } else {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000767 if (State.Stack.size() < State.StartOfLineLevel &&
768 State.NextToken->is(tok::identifier))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000769 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000770 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000771 }
772
Daniel Jasper20409152012-12-04 14:54:30 +0000773 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000774
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000775 // Exceeding column limit is bad, assign penalty.
776 if (State.Column > getColumnLimit()) {
777 unsigned ExcessCharacters = State.Column - getColumnLimit();
778 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
779 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000780
Daniel Jasperbac016b2012-12-03 18:12:45 +0000781 if (StopAt <= CurrentPenalty)
782 return UINT_MAX;
783 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000784 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000785 if (I != Memory.end()) {
786 // If this state has already been examined, we can safely return the
787 // previous result if we
788 // - have not hit the optimatization (and thus returned UINT_MAX) OR
789 // - are now computing for a smaller or equal StopAt.
790 unsigned SavedResult = I->second.first;
791 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000792 if (SavedResult != UINT_MAX)
793 return SavedResult + CurrentPenalty;
794 else if (StopAt <= SavedStopAt)
795 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000796 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000797
798 unsigned NoBreak = calcPenalty(State, false, StopAt);
799 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
800 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000801
802 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
803 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000804 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000805
806 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000807 }
808
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809 FormatStyle Style;
810 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000811 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000812 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000813 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000814 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000815
Daniel Jasper33182dd2012-12-05 14:57:28 +0000816 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000817 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000818 StateMap Memory;
819
Daniel Jasperbac016b2012-12-03 18:12:45 +0000820 OptimizationParameters Parameters;
821};
822
823/// \brief Determines extra information about the tokens comprising an
824/// \c UnwrappedLine.
825class TokenAnnotator {
826public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000827 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
828 AnnotatedLine &Line)
829 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000830
831 /// \brief A parser that gathers additional information about tokens.
832 ///
833 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
834 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
835 /// into template parameter lists.
836 class AnnotatingParser {
837 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000838 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000839 : CurrentToken(&RootToken), KeywordVirtualFound(false),
840 ColonIsObjCMethodExpr(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000841
Nico Weber6a21a552013-01-18 02:43:57 +0000842 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
843 struct ObjCSelectorRAII {
844 AnnotatingParser &P;
845 bool ColonWasObjCMethodExpr;
846
847 ObjCSelectorRAII(AnnotatingParser &P)
848 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
849
850 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
851
852 void markStart(AnnotatedToken &Left) {
853 P.ColonIsObjCMethodExpr = true;
854 Left.Type = TT_ObjCMethodExpr;
855 }
856
857 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
858 };
859
860
Daniel Jasper20409152012-12-04 14:54:30 +0000861 bool parseAngle() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000862 if (CurrentToken == NULL)
863 return false;
864 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000865 while (CurrentToken != NULL) {
866 if (CurrentToken->is(tok::greater)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000867 Left->MatchingParen = CurrentToken;
868 CurrentToken->MatchingParen = Left;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000869 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000870 next();
871 return true;
872 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000873 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
874 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000876 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
877 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000878 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000879 if (!consumeToken())
880 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000881 }
882 return false;
883 }
884
Nico Weber5096a442013-01-17 17:17:19 +0000885 bool parseParens(bool LookForDecls = false) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000886 if (CurrentToken == NULL)
887 return false;
Nico Weber6a21a552013-01-18 02:43:57 +0000888 bool StartsObjCMethodExpr = false;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000889 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber6a21a552013-01-18 02:43:57 +0000890 if (CurrentToken->is(tok::caret)) {
891 // ^( starts a block.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000892 Left->Type = TT_ObjCBlockLParen;
Nico Weber6a21a552013-01-18 02:43:57 +0000893 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
894 // @selector( starts a selector.
895 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
896 MaybeSel->Parent->is(tok::at)) {
897 StartsObjCMethodExpr = true;
898 }
899 }
900
901 ObjCSelectorRAII objCSelector(*this);
902 if (StartsObjCMethodExpr)
903 objCSelector.markStart(*Left);
904
Daniel Jasper26f7e782013-01-08 14:56:18 +0000905 while (CurrentToken != NULL) {
Nico Weber5096a442013-01-17 17:17:19 +0000906 // LookForDecls is set when "if (" has been seen. Check for
907 // 'identifier' '*' 'identifier' followed by not '=' -- this
908 // '*' has to be a binary operator but determineStarAmpUsage() will
909 // categorize it as an unary operator, so set the right type here.
910 if (LookForDecls && !CurrentToken->Children.empty()) {
911 AnnotatedToken &Prev = *CurrentToken->Parent;
912 AnnotatedToken &Next = CurrentToken->Children[0];
913 if (Prev.Parent->is(tok::identifier) &&
914 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
915 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
916 Prev.Type = TT_BinaryOperator;
917 LookForDecls = false;
918 }
919 }
920
Daniel Jasper26f7e782013-01-08 14:56:18 +0000921 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000922 Left->MatchingParen = CurrentToken;
923 CurrentToken->MatchingParen = Left;
Nico Weber6a21a552013-01-18 02:43:57 +0000924
925 if (StartsObjCMethodExpr)
926 objCSelector.markEnd(*CurrentToken);
927
Daniel Jasperbac016b2012-12-03 18:12:45 +0000928 next();
929 return true;
930 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000931 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000932 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000933 if (!consumeToken())
934 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000935 }
936 return false;
937 }
938
Daniel Jasper20409152012-12-04 14:54:30 +0000939 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000940 if (!CurrentToken)
941 return false;
942
943 // A '[' could be an index subscript (after an indentifier or after
944 // ')' or ']'), or it could be the start of an Objective-C method
945 // expression.
Nico Weber3f29fbb2013-01-21 19:29:31 +0000946 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weberbcfdd262013-01-12 06:18:40 +0000947 bool StartsObjCMethodExpr =
Nico Weber3f29fbb2013-01-21 19:29:31 +0000948 !Left->Parent || Left->Parent->is(tok::colon) ||
949 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
950 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
951 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Weberbcfdd262013-01-12 06:18:40 +0000952 true, true) > prec::Unknown;
953
Nico Weber6a21a552013-01-18 02:43:57 +0000954 ObjCSelectorRAII objCSelector(*this);
955 if (StartsObjCMethodExpr)
Nico Weber3f29fbb2013-01-21 19:29:31 +0000956 objCSelector.markStart(*Left);
Nico Weberbcfdd262013-01-12 06:18:40 +0000957
Daniel Jasper26f7e782013-01-08 14:56:18 +0000958 while (CurrentToken != NULL) {
959 if (CurrentToken->is(tok::r_square)) {
Daniel Jasperffee1712013-01-22 11:46:26 +0000960 if (!CurrentToken->Children.empty() &&
961 CurrentToken->Children[0].is(tok::l_paren)) {
962 // An ObjC method call can't be followed by an open parenthesis.
963 // FIXME: Do we incorrectly label ":" with this?
964 StartsObjCMethodExpr = false;
965 Left->Type = TT_Unknown;
966 }
Nico Weber6a21a552013-01-18 02:43:57 +0000967 if (StartsObjCMethodExpr)
968 objCSelector.markEnd(*CurrentToken);
Nico Weber05bf8272013-01-21 19:35:06 +0000969 Left->MatchingParen = CurrentToken;
970 CurrentToken->MatchingParen = Left;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000971 next();
972 return true;
973 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000974 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000975 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000976 if (!consumeToken())
977 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000978 }
979 return false;
980 }
981
Daniel Jasper700e7102013-01-10 09:26:47 +0000982 bool parseBrace() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000983 // Lines are fine to end with '{'.
984 if (CurrentToken == NULL)
985 return true;
986 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper700e7102013-01-10 09:26:47 +0000987 while (CurrentToken != NULL) {
988 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000989 Left->MatchingParen = CurrentToken;
990 CurrentToken->MatchingParen = Left;
Daniel Jasper700e7102013-01-10 09:26:47 +0000991 next();
992 return true;
993 }
994 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
995 return false;
996 if (!consumeToken())
997 return false;
998 }
Daniel Jasper700e7102013-01-10 09:26:47 +0000999 return true;
1000 }
1001
Daniel Jasper20409152012-12-04 14:54:30 +00001002 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001003 while (CurrentToken != NULL) {
1004 if (CurrentToken->is(tok::colon)) {
1005 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001006 next();
1007 return true;
1008 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001009 if (!consumeToken())
1010 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001011 }
1012 return false;
1013 }
1014
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001015 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001016 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1017 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001018 next();
1019 if (!parseAngle())
1020 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001021 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001022 return true;
1023 }
1024 return false;
1025 }
1026
Daniel Jasper1f42f112013-01-04 18:52:56 +00001027 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001028 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001029 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001030 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +00001031 case tok::plus:
1032 case tok::minus:
1033 // At the start of the line, +/- specific ObjectiveC method
1034 // declarations.
1035 if (Tok->Parent == NULL)
1036 Tok->Type = TT_ObjCMethodSpecifier;
1037 break;
Nico Weberbcfdd262013-01-12 06:18:40 +00001038 case tok::colon:
1039 // Colons from ?: are handled in parseConditional().
Daniel Jasper1f2b0782013-01-16 16:23:19 +00001040 if (Tok->Parent->is(tok::r_paren))
1041 Tok->Type = TT_CtorInitializerColon;
Nico Weberbcfdd262013-01-12 06:18:40 +00001042 if (ColonIsObjCMethodExpr)
1043 Tok->Type = TT_ObjCMethodExpr;
1044 break;
Nico Weber5096a442013-01-17 17:17:19 +00001045 case tok::kw_if:
1046 case tok::kw_while:
Manuel Klimek092a2c72013-01-23 10:09:28 +00001047 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Nico Weber5096a442013-01-17 17:17:19 +00001048 next();
1049 if (!parseParens(/*LookForDecls=*/true))
1050 return false;
1051 }
1052 break;
Nico Weber94fb7292013-01-18 05:50:57 +00001053 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001054 if (!parseParens())
1055 return false;
Nico Weber94fb7292013-01-18 05:50:57 +00001056 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001057 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001058 if (!parseSquare())
1059 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001060 break;
Daniel Jasper700e7102013-01-10 09:26:47 +00001061 case tok::l_brace:
1062 if (!parseBrace())
1063 return false;
1064 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001065 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +00001066 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +00001067 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001068 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001069 Tok->Type = TT_BinaryOperator;
1070 CurrentToken = Tok;
1071 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001072 }
1073 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001074 case tok::r_paren:
1075 case tok::r_square:
1076 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +00001077 case tok::r_brace:
1078 // Lines can start with '}'.
1079 if (Tok->Parent != NULL)
1080 return false;
1081 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001082 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001083 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001084 break;
1085 case tok::kw_operator:
Manuel Klimek092a2c72013-01-23 10:09:28 +00001086 if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001087 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001088 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001089 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1090 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001091 next();
1092 }
1093 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001094 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1095 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001096 next();
1097 }
1098 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001099 break;
1100 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +00001101 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001102 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001103 case tok::kw_template:
1104 parseTemplateDeclaration();
1105 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001106 default:
1107 break;
1108 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001109 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001110 }
1111
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001112 void parseIncludeDirective() {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001113 next();
1114 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1115 next();
1116 while (CurrentToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +00001117 if (CurrentToken->isNot(tok::comment) ||
1118 !CurrentToken->Children.empty())
1119 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001120 next();
1121 }
1122 } else {
1123 while (CurrentToken != NULL) {
1124 next();
1125 }
1126 }
1127 }
1128
1129 void parseWarningOrError() {
1130 next();
1131 // We still want to format the whitespace left of the first token of the
1132 // warning or error.
1133 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001134 while (CurrentToken != NULL) {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001135 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001136 next();
1137 }
1138 }
1139
1140 void parsePreprocessorDirective() {
1141 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001142 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001143 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001144 // Hashes in the middle of a line can lead to any strange token
1145 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001146 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001147 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001148 switch (
1149 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001150 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +00001151 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001152 parseIncludeDirective();
1153 break;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001154 case tok::pp_error:
1155 case tok::pp_warning:
1156 parseWarningOrError();
1157 break;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001158 default:
1159 break;
1160 }
1161 }
1162
Daniel Jasper71607512013-01-07 10:48:50 +00001163 LineType parseLine() {
Daniel Jasper32983272013-01-22 14:28:24 +00001164 int PeriodsAndArrows = 0;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001165 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001166 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +00001167 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001168 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001169 while (CurrentToken != NULL) {
Daniel Jasper32983272013-01-22 14:28:24 +00001170
Daniel Jasper26f7e782013-01-08 14:56:18 +00001171 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +00001172 KeywordVirtualFound = true;
Daniel Jasper32983272013-01-22 14:28:24 +00001173 if (CurrentToken->is(tok::period) || CurrentToken->is(tok::arrow))
1174 ++PeriodsAndArrows;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001175 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +00001176 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001177 }
Daniel Jasper71607512013-01-07 10:48:50 +00001178 if (KeywordVirtualFound)
1179 return LT_VirtualFunctionDecl;
Daniel Jasper32983272013-01-22 14:28:24 +00001180
1181 // Assume a builder-type call if there are 2 or more "." and "->".
1182 if (PeriodsAndArrows >= 2)
1183 return LT_BuilderTypeCall;
1184
Daniel Jasper71607512013-01-07 10:48:50 +00001185 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001186 }
1187
1188 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001189 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1190 CurrentToken = &CurrentToken->Children[0];
1191 else
1192 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001193 }
1194
1195 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001196 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +00001197 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +00001198 bool ColonIsObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001199 };
1200
Daniel Jasper26f7e782013-01-08 14:56:18 +00001201 void calculateExtraInformation(AnnotatedToken &Current) {
1202 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1203
Manuel Klimek526ed112013-01-09 15:25:02 +00001204 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001205 Current.MustBreakBefore = true;
1206 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +00001207 if (Current.Type == TT_LineComment) {
1208 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001209 } else if ((Current.Parent->is(tok::comment) &&
1210 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper487f64b2013-01-13 16:10:20 +00001211 (Current.is(tok::string_literal) &&
1212 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +00001213 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +00001214 } else {
1215 Current.MustBreakBefore = false;
1216 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001217 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001218 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001219 if (Current.MustBreakBefore)
1220 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1221 else
1222 Current.TotalLength = Current.Parent->TotalLength +
1223 Current.FormatTok.TokenLength +
1224 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001225 if (!Current.Children.empty())
1226 calculateExtraInformation(Current.Children[0]);
1227 }
1228
Daniel Jasper995e8202013-01-14 13:08:07 +00001229 void annotate() {
Daniel Jasper995e8202013-01-14 13:08:07 +00001230 AnnotatingParser Parser(Line.First);
1231 Line.Type = Parser.parseLine();
1232 if (Line.Type == LT_Invalid)
1233 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001234
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001235 determineTokenTypes(Line.First, /*IsExpression=*/ false);
Daniel Jasper71607512013-01-07 10:48:50 +00001236
Daniel Jasper995e8202013-01-14 13:08:07 +00001237 if (Line.First.Type == TT_ObjCMethodSpecifier)
1238 Line.Type = LT_ObjCMethodDecl;
1239 else if (Line.First.Type == TT_ObjCDecl)
1240 Line.Type = LT_ObjCDecl;
1241 else if (Line.First.Type == TT_ObjCProperty)
1242 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +00001243
Daniel Jasper995e8202013-01-14 13:08:07 +00001244 Line.First.SpaceRequiredBefore = true;
1245 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1246 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001247
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001248 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper995e8202013-01-14 13:08:07 +00001249 if (!Line.First.Children.empty())
1250 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001251 }
1252
1253private:
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001254 void determineTokenTypes(AnnotatedToken &Current, bool IsExpression) {
1255 if (getPrecedence(Current) == prec::Assignment) {
1256 IsExpression = true;
1257 AnnotatedToken *Previous = Current.Parent;
1258 while (Previous != NULL) {
Manuel Klimeka32a7fd2013-01-23 14:08:21 +00001259 if (Previous->Type == TT_BinaryOperator &&
1260 (Previous->is(tok::star) || Previous->is(tok::amp))) {
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001261 Previous->Type = TT_PointerOrReference;
Manuel Klimeka32a7fd2013-01-23 14:08:21 +00001262 }
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001263 Previous = Previous->Parent;
1264 }
1265 }
1266 if (Current.is(tok::kw_return) || Current.is(tok::kw_throw) ||
Daniel Jasper20d35832013-01-23 12:58:14 +00001267 (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
1268 (Current.Parent == NULL || Current.Parent->isNot(tok::kw_for))))
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001269 IsExpression = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001270
Daniel Jasper26f7e782013-01-08 14:56:18 +00001271 if (Current.Type == TT_Unknown) {
1272 if (Current.is(tok::star) || Current.is(tok::amp)) {
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001273 Current.Type = determineStarAmpUsage(Current, IsExpression);
Daniel Jasper886568d2013-01-09 08:36:49 +00001274 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1275 Current.is(tok::caret)) {
1276 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001277 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1278 Current.Type = determineIncrementUsage(Current);
1279 } else if (Current.is(tok::exclaim)) {
1280 Current.Type = TT_UnaryOperator;
1281 } else if (isBinaryOperator(Current)) {
1282 Current.Type = TT_BinaryOperator;
1283 } else if (Current.is(tok::comment)) {
1284 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1285 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +00001286 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001287 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001288 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001289 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001290 } else if (Current.is(tok::r_paren) &&
1291 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001292 Current.Parent->Type == TT_TemplateCloser) &&
1293 (Current.Children.empty() ||
1294 (Current.Children[0].isNot(tok::equal) &&
1295 Current.Children[0].isNot(tok::semi) &&
1296 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001297 // FIXME: We need to get smarter and understand more cases of casts.
1298 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001299 } else if (Current.is(tok::at) && Current.Children.size()) {
1300 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1301 case tok::objc_interface:
1302 case tok::objc_implementation:
1303 case tok::objc_protocol:
1304 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001305 break;
1306 case tok::objc_property:
1307 Current.Type = TT_ObjCProperty;
1308 break;
Nico Webered91bba2013-01-10 19:19:14 +00001309 default:
1310 break;
1311 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001312 }
1313 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001314
1315 if (!Current.Children.empty())
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001316 determineTokenTypes(Current.Children[0], IsExpression);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001317 }
1318
Daniel Jasper26f7e782013-01-08 14:56:18 +00001319 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001320 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +00001321 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001322 }
1323
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001324 /// \brief Returns the previous token ignoring comments.
1325 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1326 const AnnotatedToken *PrevToken = Tok.Parent;
1327 while (PrevToken != NULL && PrevToken->is(tok::comment))
1328 PrevToken = PrevToken->Parent;
1329 return PrevToken;
1330 }
1331
1332 /// \brief Returns the next token ignoring comments.
1333 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1334 if (Tok.Children.empty())
1335 return NULL;
1336 const AnnotatedToken *NextToken = &Tok.Children[0];
1337 while (NextToken->is(tok::comment)) {
1338 if (NextToken->Children.empty())
1339 return NULL;
1340 NextToken = &NextToken->Children[0];
1341 }
1342 return NextToken;
1343 }
1344
1345 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001346 TokenType determineStarAmpUsage(const AnnotatedToken &Tok,
1347 bool IsExpression) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001348 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1349 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001350 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001351
1352 const AnnotatedToken *NextToken = getNextToken(Tok);
1353 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001354 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001355
Daniel Jasperffee1712013-01-22 11:46:26 +00001356 if (NextToken->is(tok::l_square) && NextToken->Type != TT_ObjCMethodExpr)
1357 return TT_PointerOrReference;
1358
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001359 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1360 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1361 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1362 PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper48bd7b72013-01-16 16:04:06 +00001363 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001364 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001365
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001366 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1367 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1368 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1369 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1370 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1371 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1372 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001373 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001374
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001375 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1376 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001377 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001378
Daniel Jasper112fb272012-12-05 07:51:39 +00001379 // It is very unlikely that we are going to find a pointer or reference type
1380 // definition on the RHS of an assignment.
Daniel Jasper4bfc65a2013-01-23 12:10:53 +00001381 if (IsExpression)
Daniel Jasper71607512013-01-07 10:48:50 +00001382 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001383
Daniel Jasper71607512013-01-07 10:48:50 +00001384 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001385 }
1386
Daniel Jasper886568d2013-01-09 08:36:49 +00001387 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001388 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1389 if (PrevToken == NULL)
1390 return TT_UnaryOperator;
1391
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001392 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001393 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1394 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1395 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1396 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1397 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001398 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001399
1400 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001401 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001402 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001403
1404 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001405 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001406 }
1407
1408 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001409 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001410 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1411 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001412 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001413 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1414 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001415 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001416
Daniel Jasper71607512013-01-07 10:48:50 +00001417 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001418 }
1419
Daniel Jasper26f7e782013-01-08 14:56:18 +00001420 bool spaceRequiredBetween(const AnnotatedToken &Left,
1421 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001422 if (Right.is(tok::hashhash))
1423 return Left.is(tok::hash);
1424 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1425 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001426 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1427 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001428 if (Right.is(tok::less) &&
1429 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001430 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001431 return true;
1432 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1433 return false;
1434 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1435 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001436 if (Left.is(tok::at) &&
1437 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1438 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001439 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1440 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001441 return false;
Daniel Jasper6b825c22013-01-16 07:19:28 +00001442 if (Left.is(tok::coloncolon))
1443 return false;
1444 if (Right.is(tok::coloncolon))
1445 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001446 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1447 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001448 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001449 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001450 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1451 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001452 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001453 return Right.FormatTok.Tok.isLiteral() ||
1454 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001455 if (Right.is(tok::star) && Left.is(tok::l_paren))
1456 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001457 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1458 return false;
1459 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001460 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001461 if (Left.is(tok::period) || Right.is(tok::period))
1462 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001463 if (Left.is(tok::colon))
1464 return Left.Type != TT_ObjCMethodExpr;
1465 if (Right.is(tok::colon))
1466 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001467 if (Left.is(tok::l_paren))
1468 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001469 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001470 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001471 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001472 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001473 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1474 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001475 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001476 if (Left.is(tok::at) &&
1477 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001478 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001479 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1480 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001481 return true;
1482 }
1483
Daniel Jasper26f7e782013-01-08 14:56:18 +00001484 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001485 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001486 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1487 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001488 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001489 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001490 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001491 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weberaab60052013-01-17 06:14:50 +00001492 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001493 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001494 // Don't space between ')' and <id>
1495 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001496 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001497 // Don't space between ':' and '('
1498 return false;
1499 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001500 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001501 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1502 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001503
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001504 if (Tok.Parent->is(tok::comma))
1505 return true;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001506 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001507 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001508 if (Tok.Type == TT_OverloadedOperator)
1509 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001510 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001511 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001512 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001513 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001514 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001515 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001516 if (Tok.Parent->Type == TT_UnaryOperator ||
1517 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001518 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001519 if (Tok.Type == TT_UnaryOperator)
1520 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001521 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1522 (Tok.Parent->isNot(tok::colon) ||
1523 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001524 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1525 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001526 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1527 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001528 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001529 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001530 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001531 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001532 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001533 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001534 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001535 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001536 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001537 }
1538
Daniel Jasper26f7e782013-01-08 14:56:18 +00001539 bool canBreakBefore(const AnnotatedToken &Right) {
1540 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001541 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001542 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1543 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001544 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001545 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1546 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001547 // Don't break this identifier as ':' or identifier
1548 // before it will break.
1549 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001550 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1551 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001552 // Don't break at ':' if identifier before it can beak.
1553 return false;
1554 }
Nico Weberbcfdd262013-01-12 06:18:40 +00001555 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1556 return false;
1557 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1558 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001559 if (isObjCSelectorName(Right))
1560 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001561 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001562 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001563 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001564 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001565 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001566 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001567 return false;
1568
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001569 if (Right.Type == TT_LineComment)
Daniel Jasper487f64b2013-01-13 16:10:20 +00001570 // We rely on MustBreakBefore being set correctly here as we should not
1571 // change the "binding" behavior of a comment.
1572 return false;
1573
Daniel Jasper60ca75d2013-01-17 13:31:52 +00001574 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1575 // unless it is follow by ';', '{' or '='.
1576 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1577 Left.Parent->is(tok::r_paren))
1578 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1579 Right.isNot(tok::equal);
1580
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001581 // We only break before r_brace if there was a corresponding break before
1582 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1583 if (Right.is(tok::r_brace))
1584 return false;
1585
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001586 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001587 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001588 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1589 Left.is(tok::comma) || Right.is(tok::lessless) ||
1590 Right.is(tok::arrow) || Right.is(tok::period) ||
1591 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001592 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1593 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1594 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001595 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001596 }
1597
Daniel Jasperbac016b2012-12-03 18:12:45 +00001598 FormatStyle Style;
1599 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001600 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001601 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001602};
1603
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001604class LexerBasedFormatTokenSource : public FormatTokenSource {
1605public:
1606 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001607 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001608 IdentTable(Lex.getLangOpts()) {
1609 Lex.SetKeepWhitespaceMode(true);
1610 }
1611
1612 virtual FormatToken getNextToken() {
1613 if (GreaterStashed) {
1614 FormatTok.NewlinesBefore = 0;
1615 FormatTok.WhiteSpaceStart =
1616 FormatTok.Tok.getLocation().getLocWithOffset(1);
1617 FormatTok.WhiteSpaceLength = 0;
1618 GreaterStashed = false;
1619 return FormatTok;
1620 }
1621
1622 FormatTok = FormatToken();
1623 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001624 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001625 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001626 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1627 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001628
1629 // Consume and record whitespace until we find a significant token.
1630 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001631 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001632 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1633 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001634 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1635
1636 if (FormatTok.Tok.is(tok::eof))
1637 return FormatTok;
1638 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001639 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001640 }
Manuel Klimek95419382013-01-07 07:56:50 +00001641
1642 // Now FormatTok is the next non-whitespace token.
1643 FormatTok.TokenLength = Text.size();
1644
Manuel Klimekd4397b92013-01-04 23:34:14 +00001645 // In case the token starts with escaped newlines, we want to
1646 // take them into account as whitespace - this pattern is quite frequent
1647 // in macro definitions.
1648 // FIXME: What do we want to do with other escaped spaces, and escaped
1649 // spaces or newlines in the middle of tokens?
1650 // FIXME: Add a more explicit test.
1651 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001652 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek86721d22013-01-22 16:31:55 +00001653 // FIXME: ++FormatTok.NewlinesBefore is missing...
Manuel Klimekd4397b92013-01-04 23:34:14 +00001654 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001655 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001656 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001657 }
1658
1659 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001660 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001661 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001662 FormatTok.Tok.setKind(Info.getTokenID());
1663 }
1664
1665 if (FormatTok.Tok.is(tok::greatergreater)) {
1666 FormatTok.Tok.setKind(tok::greater);
1667 GreaterStashed = true;
1668 }
1669
1670 return FormatTok;
1671 }
1672
1673private:
1674 FormatToken FormatTok;
1675 bool GreaterStashed;
1676 Lexer &Lex;
1677 SourceManager &SourceMgr;
1678 IdentifierTable IdentTable;
1679
1680 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001681 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001682 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1683 Tok.getLength());
1684 }
1685};
1686
Daniel Jasperbac016b2012-12-03 18:12:45 +00001687class Formatter : public UnwrappedLineConsumer {
1688public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001689 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1690 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001691 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001692 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001693 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001694
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001695 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001696
Daniel Jasperbac016b2012-12-03 18:12:45 +00001697 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001698 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001699 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001700 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001701 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001702 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1703 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1704 Annotator.annotate();
1705 }
1706 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1707 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001708 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001709 const AnnotatedLine &TheLine = *I;
1710 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1711 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1712 TheLine.InPPDirective,
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001713 PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001714 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001715 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001716 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001717 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001718 PreviousEndOfLineColumn = Formatter.format();
1719 } else {
1720 // If we did not reformat this unwrapped line, the column at the end of
1721 // the last token is unchanged - thus, we can calculate the end of the
1722 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001723 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001724 SourceMgr.getSpellingColumnNumber(
1725 TheLine.Last->FormatTok.Tok.getLocation()) +
1726 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1727 SourceMgr, Lex.getLangOpts()) -
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001728 1;
1729 }
1730 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001731 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001732 }
1733
1734private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001735 /// \brief Tries to merge lines into one.
1736 ///
1737 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1738 /// if possible; note that \c I will be incremented when lines are merged.
1739 ///
1740 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001741 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001742 std::vector<AnnotatedLine>::iterator &I,
1743 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001744 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1745
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001746 // We can never merge stuff if there are trailing line comments.
1747 if (I->Last->Type == TT_LineComment)
1748 return;
1749
Manuel Klimek517e8942013-01-11 17:54:10 +00001750 // Check whether the UnwrappedLine can be put onto a single line. If
1751 // so, this is bound to be the optimal solution (by definition) and we
1752 // don't need to analyze the entire solution space.
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001753 if (I->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001754 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001755 Limit -= I->Last->TotalLength;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001756
Daniel Jasper9c8c40e2013-01-21 14:18:28 +00001757 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001758 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001759
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001760 if (I->Last->is(tok::l_brace)) {
1761 tryMergeSimpleBlock(I, E, Limit);
1762 } else if (I->First.is(tok::kw_if)) {
1763 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001764 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1765 I->First.FormatTok.IsFirst)) {
1766 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001767 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001768 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001769 }
1770
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001771 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1772 std::vector<AnnotatedLine>::iterator E,
1773 unsigned Limit) {
1774 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001775 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1776 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001777 if (I + 2 != E && (I + 2)->InPPDirective &&
1778 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1779 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001780 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001781 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001782 join(Line, *(++I));
1783 }
1784
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001785 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1786 std::vector<AnnotatedLine>::iterator E,
1787 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001788 if (!Style.AllowShortIfStatementsOnASingleLine)
1789 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001790 if ((I + 1)->InPPDirective != I->InPPDirective ||
1791 ((I + 1)->InPPDirective &&
1792 (I + 1)->First.FormatTok.HasUnescapedNewline))
1793 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001794 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001795 if (Line.Last->isNot(tok::r_paren))
1796 return;
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001797 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001798 return;
1799 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1800 return;
1801 // Only inline simple if's (no nested if or else).
1802 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1803 return;
1804 join(Line, *(++I));
1805 }
1806
1807 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1808 std::vector<AnnotatedLine>::iterator E,
1809 unsigned Limit){
Manuel Klimek517e8942013-01-11 17:54:10 +00001810 // First, check that the current line allows merging. This is the case if
1811 // we're not in a control flow statement and the last token is an opening
1812 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001813 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001814 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001815 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1816 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1817 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1818 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001819 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001820 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1821 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001822 if (!AllowedTokens)
1823 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001824
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001825 AnnotatedToken *Tok = &(I + 1)->First;
1826 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1827 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1828 Tok->SpaceRequiredBefore = false;
1829 join(Line, *(I + 1));
1830 I += 1;
1831 } else {
1832 // Check that we still have three lines and they fit into the limit.
1833 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1834 !nextTwoLinesFitInto(I, Limit))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001835 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001836
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001837 // Second, check that the next line does not contain any braces - if it
1838 // does, readability declines when putting it into a single line.
1839 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1840 return;
1841 do {
1842 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1843 return;
1844 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1845 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001846
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001847 // Last, check that the third line contains a single closing brace.
1848 Tok = &(I + 2)->First;
1849 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1850 Tok->MustBreakBefore)
1851 return;
1852
1853 join(Line, *(I + 1));
1854 join(Line, *(I + 2));
1855 I += 2;
Manuel Klimek517e8942013-01-11 17:54:10 +00001856 }
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001857 }
1858
1859 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1860 unsigned Limit) {
Manuel Klimek2f1ac412013-01-21 16:42:44 +00001861 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1862 Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001863 }
1864
Daniel Jasper995e8202013-01-14 13:08:07 +00001865 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1866 A.Last->Children.push_back(B.First);
1867 while (!A.Last->Children.empty()) {
1868 A.Last->Children[0].Parent = A.Last;
1869 A.Last = &A.Last->Children[0];
1870 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001871 }
1872
Daniel Jasper995e8202013-01-14 13:08:07 +00001873 bool touchesRanges(const AnnotatedLine &TheLine) {
1874 const FormatToken *First = &TheLine.First.FormatTok;
1875 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001876 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001877 First->Tok.getLocation(),
1878 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001879 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001880 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1881 Ranges[i].getBegin()) &&
1882 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1883 LineRange.getBegin()))
1884 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001885 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001886 return false;
1887 }
1888
1889 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001890 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001891 }
1892
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001893 /// \brief Add a new line and the required indent before the first Token
1894 /// of the \c UnwrappedLine if there was no structural parsing error.
1895 /// Returns the indent level of the \c UnwrappedLine.
1896 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1897 bool InPPDirective,
1898 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001899 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001900 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1901 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1902
1903 unsigned Newlines = std::min(Tok.NewlinesBefore,
1904 Style.MaxEmptyLinesToKeep + 1);
1905 if (Newlines == 0 && !Tok.IsFirst)
1906 Newlines = 1;
1907 unsigned Indent = Level * 2;
1908
1909 bool IsAccessModifier = false;
1910 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1911 RootToken.is(tok::kw_private))
1912 IsAccessModifier = true;
1913 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1914 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1915 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1916 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1917 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1918 IsAccessModifier = true;
1919
1920 if (IsAccessModifier &&
1921 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1922 Indent += Style.AccessModifierOffset;
1923 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001924 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001925 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001926 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1927 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001928 }
1929 return Indent;
1930 }
1931
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001932 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001933 FormatStyle Style;
1934 Lexer &Lex;
1935 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001936 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001937 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001938 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001939 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001940};
1941
1942tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1943 SourceManager &SourceMgr,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001944 std::vector<CharSourceRange> Ranges,
1945 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001946 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001947 OwningPtr<DiagnosticConsumer> DiagPrinter;
1948 if (DiagClient == 0) {
1949 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1950 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1951 DiagClient = DiagPrinter.get();
1952 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001953 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001954 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001955 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001956 Diagnostics.setSourceManager(&SourceMgr);
1957 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001958 return formatter.format();
1959}
1960
Daniel Jasper46ef8522013-01-10 13:08:12 +00001961LangOptions getFormattingLangOpts() {
1962 LangOptions LangOpts;
1963 LangOpts.CPlusPlus = 1;
1964 LangOpts.CPlusPlus11 = 1;
1965 LangOpts.Bool = 1;
1966 LangOpts.ObjC1 = 1;
1967 LangOpts.ObjC2 = 1;
1968 return LangOpts;
1969}
1970
Daniel Jaspercd162382013-01-07 13:26:07 +00001971} // namespace format
1972} // namespace clang