blob: d234006a25a5e861fd9e161991a94da5112a37c9 [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,
63 LT_PreprocessorDirective,
64 LT_VirtualFunctionDecl,
Nico Webered91bba2013-01-10 19:19:14 +000065 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Weber70848232013-01-10 21:30:42 +000066 LT_ObjCMethodDecl,
67 LT_ObjCProperty // An @property line.
Daniel Jasper71607512013-01-07 10:48:50 +000068};
69
Daniel Jasper26f7e782013-01-08 14:56:18 +000070class AnnotatedToken {
71public:
Daniel Jasperdcc2a622013-01-18 08:44:07 +000072 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimek94fc6f12013-01-10 19:17:33 +000073 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
74 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper0df6acd2013-01-16 14:59:02 +000075 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper26f7e782013-01-08 14:56:18 +000076
Daniel Jasperfeb18f52013-01-14 14:14:23 +000077 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
78 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
79
Daniel Jasper26f7e782013-01-08 14:56:18 +000080 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
81 return FormatTok.Tok.isObjCAtKeyword(Kind);
82 }
83
84 FormatToken FormatTok;
85
Daniel Jasperbac016b2012-12-03 18:12:45 +000086 TokenType Type;
87
Daniel Jasperbac016b2012-12-03 18:12:45 +000088 bool SpaceRequiredBefore;
89 bool CanBreakBefore;
90 bool MustBreakBefore;
Daniel Jasper9a64fb52013-01-02 15:08:56 +000091
92 bool ClosesTemplateDeclaration;
Daniel Jasper26f7e782013-01-08 14:56:18 +000093
Daniel Jasper0df6acd2013-01-16 14:59:02 +000094 AnnotatedToken *MatchingParen;
95
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +000096 /// \brief The total length of the line up to and including this token.
97 unsigned TotalLength;
98
Daniel Jasper26f7e782013-01-08 14:56:18 +000099 std::vector<AnnotatedToken> Children;
100 AnnotatedToken *Parent;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000101
102 const AnnotatedToken *getPreviousNoneComment() const {
103 AnnotatedToken *Tok = Parent;
104 while (Tok != NULL && Tok->is(tok::comment))
105 Tok = Tok->Parent;
106 return Tok;
107 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000108};
109
Daniel Jasper995e8202013-01-14 13:08:07 +0000110class AnnotatedLine {
111public:
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000112 AnnotatedLine(const UnwrappedLine &Line)
113 : First(Line.Tokens.front()), Level(Line.Level),
114 InPPDirective(Line.InPPDirective) {
115 assert(!Line.Tokens.empty());
116 AnnotatedToken *Current = &First;
117 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
118 E = Line.Tokens.end();
119 I != E; ++I) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000120 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jaspercbb6c412013-01-16 09:10:19 +0000121 Current->Children[0].Parent = Current;
122 Current = &Current->Children[0];
123 }
124 Last = Current;
125 }
126 AnnotatedLine(const AnnotatedLine &Other)
127 : First(Other.First), Type(Other.Type), Level(Other.Level),
128 InPPDirective(Other.InPPDirective) {
129 Last = &First;
130 while (!Last->Children.empty()) {
131 Last->Children[0].Parent = Last;
132 Last = &Last->Children[0];
133 }
134 }
135
Daniel Jasper995e8202013-01-14 13:08:07 +0000136 AnnotatedToken First;
137 AnnotatedToken *Last;
138
139 LineType Type;
140 unsigned Level;
141 bool InPPDirective;
142};
143
Daniel Jasper26f7e782013-01-08 14:56:18 +0000144static prec::Level getPrecedence(const AnnotatedToken &Tok) {
145 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jaspercf225b62012-12-24 13:43:52 +0000146}
147
Daniel Jasperbac016b2012-12-03 18:12:45 +0000148FormatStyle getLLVMStyle() {
149 FormatStyle LLVMStyle;
150 LLVMStyle.ColumnLimit = 80;
151 LLVMStyle.MaxEmptyLinesToKeep = 1;
152 LLVMStyle.PointerAndReferenceBindToType = false;
153 LLVMStyle.AccessModifierOffset = -2;
154 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko15757312012-12-06 18:03:27 +0000155 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000156 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000157 LLVMStyle.BinPackParameters = true;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000158 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000160 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000161 return LLVMStyle;
162}
163
164FormatStyle getGoogleStyle() {
165 FormatStyle GoogleStyle;
166 GoogleStyle.ColumnLimit = 80;
167 GoogleStyle.MaxEmptyLinesToKeep = 1;
168 GoogleStyle.PointerAndReferenceBindToType = true;
169 GoogleStyle.AccessModifierOffset = -1;
170 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko15757312012-12-06 18:03:27 +0000171 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000172 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000173 GoogleStyle.BinPackParameters = false;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000174 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperdf3736a2013-01-16 15:44:34 +0000175 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Weber5f500df2013-01-10 20:12:55 +0000176 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000177 return GoogleStyle;
178}
179
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +0000180FormatStyle getChromiumStyle() {
181 FormatStyle ChromiumStyle = getGoogleStyle();
182 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
183 return ChromiumStyle;
184}
185
Daniel Jasperbac016b2012-12-03 18:12:45 +0000186struct OptimizationParameters {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000187 unsigned PenaltyIndentLevel;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000188 unsigned PenaltyLevelDecrease;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000189 unsigned PenaltyExcessCharacter;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000190};
191
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000192/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000193///
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000194/// This includes special handling for certain constructs, e.g. the alignment of
195/// trailing line comments.
196class WhitespaceManager {
197public:
198 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
199
200 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
201 /// each \c AnnotatedToken.
202 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
203 unsigned Spaces, unsigned WhitespaceStartColumn,
204 const FormatStyle &Style) {
205 if (Tok.Type == TT_LineComment && NewLines < 2 &&
206 (Tok.Parent != NULL || !Comments.empty())) {
207 if (Style.ColumnLimit >=
208 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
209 Comments.push_back(StoredComment());
210 Comments.back().Tok = Tok.FormatTok;
211 Comments.back().Spaces = Spaces;
212 Comments.back().NewLines = NewLines;
213 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
214 Comments.back().MaxColumn = Style.ColumnLimit -
215 Spaces - Tok.FormatTok.TokenLength;
216 return;
217 }
218 } else if (NewLines == 0 && Tok.Children.empty() &&
219 Tok.Type != TT_LineComment) {
220 alignComments();
221 }
222 storeReplacement(Tok.FormatTok,
223 std::string(NewLines, '\n') + std::string(Spaces, ' '));
224 }
225
226 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
227 /// backslashes to escape newlines inside a preprocessor directive.
228 ///
229 /// This function and \c replaceWhitespace have the same behavior if
230 /// \c Newlines == 0.
231 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
232 unsigned Spaces, unsigned WhitespaceStartColumn,
233 const FormatStyle &Style) {
234 std::string NewLineText;
235 if (NewLines > 0) {
236 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
237 WhitespaceStartColumn);
238 for (unsigned i = 0; i < NewLines; ++i) {
239 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
240 NewLineText += "\\\n";
241 Offset = 0;
242 }
243 }
244 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
245 }
246
247 /// \brief Returns all the \c Replacements created during formatting.
248 const tooling::Replacements &generateReplacements() {
249 alignComments();
250 return Replaces;
251 }
252
253private:
254 /// \brief Structure to store a comment for later layout and alignment.
255 struct StoredComment {
256 FormatToken Tok;
257 unsigned MinColumn;
258 unsigned MaxColumn;
259 unsigned NewLines;
260 unsigned Spaces;
261 };
262 SmallVector<StoredComment, 16> Comments;
263 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
264
265 /// \brief Try to align all stashed comments.
266 void alignComments() {
267 unsigned MinColumn = 0;
268 unsigned MaxColumn = UINT_MAX;
269 comment_iterator Start = Comments.begin();
270 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
271 ++I) {
272 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
273 alignComments(Start, I, MinColumn);
274 MinColumn = I->MinColumn;
275 MaxColumn = I->MaxColumn;
276 Start = I;
277 } else {
278 MinColumn = std::max(MinColumn, I->MinColumn);
279 MaxColumn = std::min(MaxColumn, I->MaxColumn);
280 }
281 }
282 alignComments(Start, Comments.end(), MinColumn);
283 Comments.clear();
284 }
285
286 /// \brief Put all the comments between \p I and \p E into \p Column.
287 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
288 while (I != E) {
289 unsigned Spaces = I->Spaces + Column - I->MinColumn;
290 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
291 std::string(Spaces, ' '));
292 ++I;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000293 }
294 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000295
296 /// \brief Stores \p Text as the replacement for the whitespace in front of
297 /// \p Tok.
298 void storeReplacement(const FormatToken &Tok, const std::string Text) {
299 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
300 Tok.WhiteSpaceLength, Text));
301 }
302
303 SourceManager &SourceMgr;
304 tooling::Replacements Replaces;
305};
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000306
Nico Webere8ccc812013-01-12 22:48:47 +0000307/// \brief Returns if a token is an Objective-C selector name.
308///
Nico Weberea865632013-01-12 22:51:13 +0000309/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Webere8ccc812013-01-12 22:48:47 +0000310static bool isObjCSelectorName(const AnnotatedToken &Tok) {
311 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
312 Tok.Children[0].is(tok::colon) &&
313 Tok.Children[0].Type == TT_ObjCMethodExpr;
314}
315
Daniel Jasperbac016b2012-12-03 18:12:45 +0000316class UnwrappedLineFormatter {
317public:
Manuel Klimek94fc6f12013-01-10 19:17:33 +0000318 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper995e8202013-01-14 13:08:07 +0000319 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000320 const AnnotatedToken &RootToken,
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000321 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper1321eb52012-12-18 21:05:13 +0000322 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000323 FirstIndent(FirstIndent), RootToken(RootToken),
324 Whitespaces(Whitespaces) {
Daniel Jasperc79afda2013-01-18 10:56:38 +0000325 Parameters.PenaltyIndentLevel = 20;
Daniel Jasper46a46a22013-01-07 07:13:20 +0000326 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000327 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000328 }
329
Manuel Klimekd4397b92013-01-04 23:34:14 +0000330 /// \brief Formats an \c UnwrappedLine.
331 ///
332 /// \returns The column after the last token in the last line of the
333 /// \c UnwrappedLine.
334 unsigned format() {
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000335 // Initialize state dependent on indent.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000336 LineState State;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000337 State.Column = FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000338 State.NextToken = &RootToken;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000339 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000340 State.ForLoopVariablePos = 0;
341 State.LineContainsContinuedForLoopSection = false;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000342 State.StartOfLineLevel = 1;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000343
Manuel Klimekca547db2013-01-16 14:55:28 +0000344 DEBUG({
345 DebugTokenState(*State.NextToken);
346 });
347
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000348 // The first token has already been indented and thus consumed.
349 moveStateToNextToken(State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000350
351 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000352 while (State.NextToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +0000353 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
354 // Calculating the column is important for aligning trailing comments.
355 // FIXME: This does not seem to happen in conjunction with escaped
356 // newlines. If it does, fix!
357 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
358 State.NextToken->FormatTok.TokenLength;
359 State.NextToken = State.NextToken->Children.empty() ? NULL :
360 &State.NextToken->Children[0];
361 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper1321eb52012-12-18 21:05:13 +0000362 addTokenToState(false, false, State);
363 } else {
364 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
365 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimekca547db2013-01-16 14:55:28 +0000366 DEBUG({
367 if (Break < NoBreak)
368 llvm::errs() << "\n";
369 else
370 llvm::errs() << " ";
371 llvm::errs() << "<";
372 DebugPenalty(Break, Break < NoBreak);
373 llvm::errs() << "/";
374 DebugPenalty(NoBreak, !(Break < NoBreak));
375 llvm::errs() << "> ";
376 DebugTokenState(*State.NextToken);
377 });
Daniel Jasper1321eb52012-12-18 21:05:13 +0000378 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000379 if (State.NextToken != NULL &&
380 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
381 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000382 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000383 State.Stack.back().BreakAfterComma = true;
384 }
Daniel Jasper1321eb52012-12-18 21:05:13 +0000385 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000386 }
Manuel Klimekca547db2013-01-16 14:55:28 +0000387 DEBUG(llvm::errs() << "\n");
Manuel Klimekd4397b92013-01-04 23:34:14 +0000388 return State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000389 }
390
391private:
Manuel Klimekca547db2013-01-16 14:55:28 +0000392 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
393 const Token &Tok = AnnotatedTok.FormatTok.Tok;
394 llvm::errs()
395 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
396 Tok.getLength());
397 llvm::errs();
398 }
399
400 void DebugPenalty(unsigned Penalty, bool Winner) {
401 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
402 if (Penalty == UINT_MAX)
403 llvm::errs() << "MAX";
404 else
405 llvm::errs() << Penalty;
406 llvm::errs().resetColor();
407 }
408
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000409 struct ParenState {
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000410 ParenState(unsigned Indent, unsigned LastSpace)
411 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000412 BreakBeforeClosingBrace(false), BreakAfterComma(false),
413 HasMultiParameterLine(false) {}
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000414
Daniel Jasperbac016b2012-12-03 18:12:45 +0000415 /// \brief The position to which a specific parenthesis level needs to be
416 /// indented.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000417 unsigned Indent;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000418
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000419 /// \brief The position of the last space on each level.
420 ///
421 /// Used e.g. to break like:
422 /// functionCall(Parameter, otherCall(
423 /// OtherParameter));
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000424 unsigned LastSpace;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000425
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000426 /// \brief The position the first "<<" operator encountered on each level.
427 ///
428 /// Used to align "<<" operators. 0 if no such operator has been encountered
429 /// on a level.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000430 unsigned FirstLessLess;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000431
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000432 /// \brief Whether a newline needs to be inserted before the block's closing
433 /// brace.
434 ///
435 /// We only want to insert a newline before the closing brace if there also
436 /// was a newline after the beginning left brace.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000437 bool BreakBeforeClosingBrace;
438
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000439 bool BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000440 bool HasMultiParameterLine;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000441
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000442 bool operator<(const ParenState &Other) const {
443 if (Indent != Other.Indent)
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000444 return Indent < Other.Indent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000445 if (LastSpace != Other.LastSpace)
446 return LastSpace < Other.LastSpace;
447 if (FirstLessLess != Other.FirstLessLess)
448 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000449 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
450 return BreakBeforeClosingBrace;
Daniel Jasperb3123142013-01-12 07:36:22 +0000451 if (BreakAfterComma != Other.BreakAfterComma)
452 return BreakAfterComma;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000453 if (HasMultiParameterLine != Other.HasMultiParameterLine)
454 return HasMultiParameterLine;
Daniel Jasperb3123142013-01-12 07:36:22 +0000455 return false;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000456 }
457 };
458
459 /// \brief The current state when indenting a unwrapped line.
460 ///
461 /// As the indenting tries different combinations this is copied by value.
462 struct LineState {
463 /// \brief The number of used columns in the current line.
464 unsigned Column;
465
466 /// \brief The token that needs to be next formatted.
467 const AnnotatedToken *NextToken;
468
469 /// \brief The parenthesis level of the first token on the current line.
470 unsigned StartOfLineLevel;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000471
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000472 /// \brief The column of the first variable in a for-loop declaration.
473 ///
474 /// Used to align the second variable if necessary.
475 unsigned ForLoopVariablePos;
476
477 /// \brief \c true if this line contains a continued for-loop section.
478 bool LineContainsContinuedForLoopSection;
479
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000480 /// \brief A stack keeping track of properties applying to parenthesis
481 /// levels.
482 std::vector<ParenState> Stack;
483
484 /// \brief Comparison operator to be able to used \c LineState in \c map.
485 bool operator<(const LineState &Other) const {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000486 if (Other.NextToken != NextToken)
487 return Other.NextToken > NextToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000488 if (Other.Column != Column)
489 return Other.Column > Column;
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000490 if (Other.StartOfLineLevel != StartOfLineLevel)
491 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000492 if (Other.ForLoopVariablePos != ForLoopVariablePos)
493 return Other.ForLoopVariablePos < ForLoopVariablePos;
494 if (Other.LineContainsContinuedForLoopSection !=
495 LineContainsContinuedForLoopSection)
496 return LineContainsContinuedForLoopSection;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000497 return Other.Stack < Stack;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000498 }
499 };
500
Daniel Jasper20409152012-12-04 14:54:30 +0000501 /// \brief Appends the next token to \p State and updates information
502 /// necessary for indentation.
503 ///
504 /// Puts the token on the current line if \p Newline is \c true and adds a
505 /// line break and necessary indentation otherwise.
506 ///
507 /// If \p DryRun is \c false, also creates and stores the required
508 /// \c Replacement.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000509 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000510 const AnnotatedToken &Current = *State.NextToken;
511 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000512 assert(State.Stack.size());
513 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000514
515 if (Newline) {
Manuel Klimek060143e2013-01-02 18:33:23 +0000516 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimekbb42bf12013-01-10 11:52:21 +0000517 if (Current.is(tok::r_brace)) {
518 State.Column = Line.Level * 2;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000519 } else if (Current.is(tok::string_literal) &&
520 Previous.is(tok::string_literal)) {
521 State.Column = State.Column - Previous.FormatTok.TokenLength;
522 } else if (Current.is(tok::lessless) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000523 State.Stack[ParenLevel].FirstLessLess != 0) {
524 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000525 } else if (ParenLevel != 0 &&
Daniel Jasper9c837d02013-01-09 07:06:56 +0000526 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
527 Current.is(tok::period) || Previous.is(tok::question) ||
528 Previous.Type == TT_ConditionalExpr)) {
529 // Indent and extra 4 spaces after if we know the current expression is
530 // continued. Don't do that on the top level, as we already indent 4
531 // there.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000532 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper9c837d02013-01-09 07:06:56 +0000533 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000534 State.Column = State.ForLoopVariablePos;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000535 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000536 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000537 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000538 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000539 }
540
Manuel Klimek2851c162013-01-10 14:36:46 +0000541 // A line starting with a closing brace is assumed to be correct for the
542 // same level as before the opening brace.
543 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000544
Daniel Jasper26f7e782013-01-08 14:56:18 +0000545 if (RootToken.is(tok::kw_for))
Daniel Jasper9c837d02013-01-09 07:06:56 +0000546 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper20409152012-12-04 14:54:30 +0000547
Manuel Klimek060143e2013-01-02 18:33:23 +0000548 if (!DryRun) {
549 if (!Line.InPPDirective)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000550 Whitespaces.replaceWhitespace(Current, 1, State.Column,
551 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000552 else
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000553 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
554 WhitespaceStartColumn, Style);
Manuel Klimek060143e2013-01-02 18:33:23 +0000555 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000556
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000557 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Weberf681fa82013-01-12 07:05:25 +0000558 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000559 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000560 } else {
Daniel Jasper9c837d02013-01-09 07:06:56 +0000561 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
562 State.ForLoopVariablePos = State.Column -
563 Previous.FormatTok.TokenLength;
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000564
Daniel Jasper26f7e782013-01-08 14:56:18 +0000565 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
566 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper7ad4eff2013-01-07 11:09:06 +0000567 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper20409152012-12-04 14:54:30 +0000568
Daniel Jasperbac016b2012-12-03 18:12:45 +0000569 if (!DryRun)
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000570 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper20409152012-12-04 14:54:30 +0000571
Daniel Jasper3fc0bb72013-01-09 10:40:23 +0000572 // FIXME: Do we need to do this for assignments nested in other
573 // expressions?
574 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper9cda8002013-01-07 13:08:40 +0000575 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper9c837d02013-01-09 07:06:56 +0000576 Previous.is(tok::kw_return)))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000577 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper7d19bc22013-01-11 14:23:32 +0000578 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +0000579 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000580 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000581 if (Current.getPreviousNoneComment()->is(tok::comma) &&
582 Current.isNot(tok::comment))
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000583 State.Stack[ParenLevel].HasMultiParameterLine = true;
584
Daniel Jasper1321eb52012-12-18 21:05:13 +0000585
Daniel Jasper9cda8002013-01-07 13:08:40 +0000586 // Top-level spaces that are not part of assignments are exempt as that
587 // mostly leads to better results.
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000588 State.Column += Spaces;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000589 if (Spaces > 0 &&
590 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000591 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000592 }
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000593
594 // If we break after an {, we should also break before the corresponding }.
595 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000596 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000597
598 // If we are breaking after '(', '{', '<' or ',', we need to break after
599 // future commas as well to avoid bin packing.
600 if (!Style.BinPackParameters && Newline &&
601 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
602 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
603 State.Stack.back().BreakAfterComma = true;
604
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000605 moveStateToNextToken(State);
Daniel Jasper20409152012-12-04 14:54:30 +0000606 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000607
Daniel Jasper20409152012-12-04 14:54:30 +0000608 /// \brief Mark the next token as consumed in \p State and modify its stacks
609 /// accordingly.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000610 void moveStateToNextToken(LineState &State) {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000611 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000612 assert(State.Stack.size());
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000613
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000614 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
615 State.Stack.back().FirstLessLess = State.Column;
Daniel Jasper3b5943f2012-12-06 09:56:08 +0000616
Daniel Jaspercf225b62012-12-24 13:43:52 +0000617 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper20409152012-12-04 14:54:30 +0000618 // prepare for the following tokens.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000619 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
620 Current.is(tok::l_brace) ||
621 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000622 unsigned NewIndent;
Manuel Klimek2851c162013-01-10 14:36:46 +0000623 if (Current.is(tok::l_brace)) {
624 // FIXME: This does not work with nested static initializers.
625 // Implement a better handling for static initializers and similar
626 // constructs.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000627 NewIndent = Line.Level * 2 + 2;
Manuel Klimek2851c162013-01-10 14:36:46 +0000628 } else {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000629 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek2851c162013-01-10 14:36:46 +0000630 }
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000631 State.Stack.push_back(
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000632 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000633
634 // If the entire set of parameters will not fit on the current line, we
635 // will need to break after commas on this level to avoid bin-packing.
636 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
637 !Current.Children.empty()) {
638 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
639 Current.MatchingParen->TotalLength -
640 Current.Children[0].TotalLength) {
641 State.Stack.back().BreakAfterComma = true;
642 }
643 }
Daniel Jasper20409152012-12-04 14:54:30 +0000644 }
645
Daniel Jaspercf225b62012-12-24 13:43:52 +0000646 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper20409152012-12-04 14:54:30 +0000647 // stacks.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000648 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
649 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
650 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000651 State.Stack.pop_back();
Daniel Jasperbac016b2012-12-03 18:12:45 +0000652 }
Manuel Klimek2851c162013-01-10 14:36:46 +0000653
Daniel Jasper26f7e782013-01-08 14:56:18 +0000654 if (State.NextToken->Children.empty())
655 State.NextToken = NULL;
656 else
657 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek2851c162013-01-10 14:36:46 +0000658
659 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000660 }
661
Nico Weberdecf7bc2013-01-07 15:15:29 +0000662 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000663 unsigned splitPenalty(const AnnotatedToken &Tok) {
664 const AnnotatedToken &Left = Tok;
665 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000666
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000667 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
668 return 50;
669 if (Left.is(tok::equal) && Right.is(tok::l_brace))
670 return 150;
671
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000672 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000673 if (RootToken.is(tok::kw_for) &&
674 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000675 return 20;
676
Daniel Jasperc79afda2013-01-18 10:56:38 +0000677 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000678 return 0;
Nico Webere8ccc812013-01-12 22:48:47 +0000679
680 // In Objective-C method expressions, prefer breaking before "param:" over
681 // breaking after it.
682 if (isObjCSelectorName(Right))
683 return 0;
684 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
685 return 20;
686
Daniel Jasper26f7e782013-01-08 14:56:18 +0000687 if (Left.is(tok::l_paren))
Daniel Jasper723f0302013-01-02 14:40:02 +0000688 return 20;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000689
Daniel Jasper9c837d02013-01-09 07:06:56 +0000690 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
691 return prec::Assignment;
Daniel Jasper9cda8002013-01-07 13:08:40 +0000692 prec::Level Level = getPrecedence(Left);
693
694 // Breaking after an assignment leads to a bad result as the two sides of
695 // the assignment are visually very close together.
696 if (Level == prec::Assignment)
697 return 50;
698
Daniel Jaspere2c7acf2012-12-24 00:13:23 +0000699 if (Level != prec::Unknown)
700 return Level;
701
Daniel Jasperc79afda2013-01-18 10:56:38 +0000702 if (Right.is(tok::arrow) || Right.is(tok::period)) {
703 if (Left.is(tok::r_paren))
704 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasper46a46a22013-01-07 07:13:20 +0000705 return 150;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000706 }
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000707
Daniel Jasperbac016b2012-12-03 18:12:45 +0000708 return 3;
709 }
710
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000711 unsigned getColumnLimit() {
712 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
713 }
714
Daniel Jasperbac016b2012-12-03 18:12:45 +0000715 /// \brief Calculate the number of lines needed to format the remaining part
716 /// of the unwrapped line.
717 ///
718 /// Assumes the formatting so far has led to
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000719 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperbac016b2012-12-03 18:12:45 +0000720 /// added after the previous token.
721 ///
722 /// \param StopAt is used for optimization. If we can determine that we'll
723 /// definitely need at least \p StopAt additional lines, we already know of a
724 /// better solution.
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000725 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperbac016b2012-12-03 18:12:45 +0000726 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper26f7e782013-01-08 14:56:18 +0000727 if (State.NextToken == NULL)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000728 return 0;
729
Daniel Jasper26f7e782013-01-08 14:56:18 +0000730 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperbac016b2012-12-03 18:12:45 +0000731 return UINT_MAX;
Manuel Klimek2c7739e2013-01-14 16:41:43 +0000732 if (NewLine && !State.NextToken->CanBreakBefore &&
733 !(State.NextToken->is(tok::r_brace) &&
734 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000735 return UINT_MAX;
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000736 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000737 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimekc8c8a472013-01-10 15:58:26 +0000738 return UINT_MAX;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000739 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jaspera324a0e2012-12-21 14:37:20 +0000740 State.LineContainsContinuedForLoopSection)
741 return UINT_MAX;
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000742 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper2c6cc482013-01-17 12:53:34 +0000743 State.NextToken->isNot(tok::comment) &&
Daniel Jasper7e9bf8c2013-01-11 11:37:55 +0000744 State.Stack.back().BreakAfterComma)
745 return UINT_MAX;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000746 // Trying to insert a parameter on a new line if there are already more than
747 // one parameter on the current line is bin packing.
748 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
749 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
750 return UINT_MAX;
Daniel Jasperc79afda2013-01-18 10:56:38 +0000751 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
752 (State.NextToken->Parent->ClosesTemplateDeclaration &&
753 State.Stack.size() == 1)))
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +0000754 return UINT_MAX;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000755
Daniel Jasper33182dd2012-12-05 14:57:28 +0000756 unsigned CurrentPenalty = 0;
757 if (NewLine) {
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000758 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper26f7e782013-01-08 14:56:18 +0000759 splitPenalty(*State.NextToken->Parent);
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000760 } else {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000761 if (State.Stack.size() < State.StartOfLineLevel &&
762 State.NextToken->is(tok::identifier))
Daniel Jaspera4974cf2012-12-24 16:43:00 +0000763 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000764 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasper33182dd2012-12-05 14:57:28 +0000765 }
766
Daniel Jasper20409152012-12-04 14:54:30 +0000767 addTokenToState(NewLine, true, State);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000768
Daniel Jasperceb99ab2013-01-09 10:16:05 +0000769 // Exceeding column limit is bad, assign penalty.
770 if (State.Column > getColumnLimit()) {
771 unsigned ExcessCharacters = State.Column - getColumnLimit();
772 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
773 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000774
Daniel Jasperbac016b2012-12-03 18:12:45 +0000775 if (StopAt <= CurrentPenalty)
776 return UINT_MAX;
777 StopAt -= CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000778 StateMap::iterator I = Memory.find(State);
Daniel Jasper33182dd2012-12-05 14:57:28 +0000779 if (I != Memory.end()) {
780 // If this state has already been examined, we can safely return the
781 // previous result if we
782 // - have not hit the optimatization (and thus returned UINT_MAX) OR
783 // - are now computing for a smaller or equal StopAt.
784 unsigned SavedResult = I->second.first;
785 unsigned SavedStopAt = I->second.second;
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000786 if (SavedResult != UINT_MAX)
787 return SavedResult + CurrentPenalty;
788 else if (StopAt <= SavedStopAt)
789 return UINT_MAX;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000790 }
Daniel Jasperbac016b2012-12-03 18:12:45 +0000791
792 unsigned NoBreak = calcPenalty(State, false, StopAt);
793 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
794 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000795
796 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
797 // can depend on 'NewLine'.
Daniel Jasper33182dd2012-12-05 14:57:28 +0000798 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper9a0b4942012-12-17 14:34:14 +0000799
800 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000801 }
802
Daniel Jasperbac016b2012-12-03 18:12:45 +0000803 FormatStyle Style;
804 SourceManager &SourceMgr;
Daniel Jasper995e8202013-01-14 13:08:07 +0000805 const AnnotatedLine &Line;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +0000806 const unsigned FirstIndent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000807 const AnnotatedToken &RootToken;
Daniel Jasperdcc2a622013-01-18 08:44:07 +0000808 WhitespaceManager &Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000809
Daniel Jasper33182dd2012-12-05 14:57:28 +0000810 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper604eb4c2013-01-11 10:22:12 +0000811 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasper33182dd2012-12-05 14:57:28 +0000812 StateMap Memory;
813
Daniel Jasperbac016b2012-12-03 18:12:45 +0000814 OptimizationParameters Parameters;
815};
816
817/// \brief Determines extra information about the tokens comprising an
818/// \c UnwrappedLine.
819class TokenAnnotator {
820public:
Daniel Jasper995e8202013-01-14 13:08:07 +0000821 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
822 AnnotatedLine &Line)
823 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000824
825 /// \brief A parser that gathers additional information about tokens.
826 ///
827 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
828 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
829 /// into template parameter lists.
830 class AnnotatingParser {
831 public:
Daniel Jasper26f7e782013-01-08 14:56:18 +0000832 AnnotatingParser(AnnotatedToken &RootToken)
Nico Weberbcfdd262013-01-12 06:18:40 +0000833 : CurrentToken(&RootToken), KeywordVirtualFound(false),
834 ColonIsObjCMethodExpr(false) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +0000835
Nico Weber6a21a552013-01-18 02:43:57 +0000836 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
837 struct ObjCSelectorRAII {
838 AnnotatingParser &P;
839 bool ColonWasObjCMethodExpr;
840
841 ObjCSelectorRAII(AnnotatingParser &P)
842 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
843
844 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
845
846 void markStart(AnnotatedToken &Left) {
847 P.ColonIsObjCMethodExpr = true;
848 Left.Type = TT_ObjCMethodExpr;
849 }
850
851 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
852 };
853
854
Daniel Jasper20409152012-12-04 14:54:30 +0000855 bool parseAngle() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000856 if (CurrentToken == NULL)
857 return false;
858 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000859 while (CurrentToken != NULL) {
860 if (CurrentToken->is(tok::greater)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000861 Left->MatchingParen = CurrentToken;
862 CurrentToken->MatchingParen = Left;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000863 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000864 next();
865 return true;
866 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000867 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
868 CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000869 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +0000870 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
871 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000872 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000873 if (!consumeToken())
874 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000875 }
876 return false;
877 }
878
Nico Weber5096a442013-01-17 17:17:19 +0000879 bool parseParens(bool LookForDecls = false) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000880 if (CurrentToken == NULL)
881 return false;
Nico Weber6a21a552013-01-18 02:43:57 +0000882 bool StartsObjCMethodExpr = false;
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000883 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber6a21a552013-01-18 02:43:57 +0000884 if (CurrentToken->is(tok::caret)) {
885 // ^( starts a block.
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000886 Left->Type = TT_ObjCBlockLParen;
Nico Weber6a21a552013-01-18 02:43:57 +0000887 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
888 // @selector( starts a selector.
889 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
890 MaybeSel->Parent->is(tok::at)) {
891 StartsObjCMethodExpr = true;
892 }
893 }
894
895 ObjCSelectorRAII objCSelector(*this);
896 if (StartsObjCMethodExpr)
897 objCSelector.markStart(*Left);
898
Daniel Jasper26f7e782013-01-08 14:56:18 +0000899 while (CurrentToken != NULL) {
Nico Weber5096a442013-01-17 17:17:19 +0000900 // LookForDecls is set when "if (" has been seen. Check for
901 // 'identifier' '*' 'identifier' followed by not '=' -- this
902 // '*' has to be a binary operator but determineStarAmpUsage() will
903 // categorize it as an unary operator, so set the right type here.
904 if (LookForDecls && !CurrentToken->Children.empty()) {
905 AnnotatedToken &Prev = *CurrentToken->Parent;
906 AnnotatedToken &Next = CurrentToken->Children[0];
907 if (Prev.Parent->is(tok::identifier) &&
908 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
909 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
910 Prev.Type = TT_BinaryOperator;
911 LookForDecls = false;
912 }
913 }
914
Daniel Jasper26f7e782013-01-08 14:56:18 +0000915 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000916 Left->MatchingParen = CurrentToken;
917 CurrentToken->MatchingParen = Left;
Nico Weber6a21a552013-01-18 02:43:57 +0000918
919 if (StartsObjCMethodExpr)
920 objCSelector.markEnd(*CurrentToken);
921
Daniel Jasperbac016b2012-12-03 18:12:45 +0000922 next();
923 return true;
924 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000925 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000926 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000927 if (!consumeToken())
928 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000929 }
930 return false;
931 }
932
Daniel Jasper20409152012-12-04 14:54:30 +0000933 bool parseSquare() {
Nico Weberbcfdd262013-01-12 06:18:40 +0000934 if (!CurrentToken)
935 return false;
936
937 // A '[' could be an index subscript (after an indentifier or after
938 // ')' or ']'), or it could be the start of an Objective-C method
939 // expression.
940 AnnotatedToken *LSquare = CurrentToken->Parent;
941 bool StartsObjCMethodExpr =
942 !LSquare->Parent || LSquare->Parent->is(tok::colon) ||
943 LSquare->Parent->is(tok::l_square) ||
944 LSquare->Parent->is(tok::l_paren) ||
945 LSquare->Parent->is(tok::kw_return) ||
946 LSquare->Parent->is(tok::kw_throw) ||
947 getBinOpPrecedence(LSquare->Parent->FormatTok.Tok.getKind(),
948 true, true) > prec::Unknown;
949
Nico Weber6a21a552013-01-18 02:43:57 +0000950 ObjCSelectorRAII objCSelector(*this);
951 if (StartsObjCMethodExpr)
952 objCSelector.markStart(*LSquare);
Nico Weberbcfdd262013-01-12 06:18:40 +0000953
Daniel Jasper26f7e782013-01-08 14:56:18 +0000954 while (CurrentToken != NULL) {
955 if (CurrentToken->is(tok::r_square)) {
Nico Weber6a21a552013-01-18 02:43:57 +0000956 if (StartsObjCMethodExpr)
957 objCSelector.markEnd(*CurrentToken);
Daniel Jasperbac016b2012-12-03 18:12:45 +0000958 next();
959 return true;
960 }
Daniel Jasper26f7e782013-01-08 14:56:18 +0000961 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperbac016b2012-12-03 18:12:45 +0000962 return false;
Daniel Jasper1f42f112013-01-04 18:52:56 +0000963 if (!consumeToken())
964 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000965 }
966 return false;
967 }
968
Daniel Jasper700e7102013-01-10 09:26:47 +0000969 bool parseBrace() {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000970 // Lines are fine to end with '{'.
971 if (CurrentToken == NULL)
972 return true;
973 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper700e7102013-01-10 09:26:47 +0000974 while (CurrentToken != NULL) {
975 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper0df6acd2013-01-16 14:59:02 +0000976 Left->MatchingParen = CurrentToken;
977 CurrentToken->MatchingParen = Left;
Daniel Jasper700e7102013-01-10 09:26:47 +0000978 next();
979 return true;
980 }
981 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
982 return false;
983 if (!consumeToken())
984 return false;
985 }
Daniel Jasper700e7102013-01-10 09:26:47 +0000986 return true;
987 }
988
Daniel Jasper20409152012-12-04 14:54:30 +0000989 bool parseConditional() {
Daniel Jasper26f7e782013-01-08 14:56:18 +0000990 while (CurrentToken != NULL) {
991 if (CurrentToken->is(tok::colon)) {
992 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000993 next();
994 return true;
995 }
Daniel Jasper1f42f112013-01-04 18:52:56 +0000996 if (!consumeToken())
997 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +0000998 }
999 return false;
1000 }
1001
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001002 bool parseTemplateDeclaration() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001003 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1004 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001005 next();
1006 if (!parseAngle())
1007 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001008 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001009 parseLine();
1010 return true;
1011 }
1012 return false;
1013 }
1014
Daniel Jasper1f42f112013-01-04 18:52:56 +00001015 bool consumeToken() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001016 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001017 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001018 switch (Tok->FormatTok.Tok.getKind()) {
Nico Webercd52bda2013-01-10 23:11:41 +00001019 case tok::plus:
1020 case tok::minus:
1021 // At the start of the line, +/- specific ObjectiveC method
1022 // declarations.
1023 if (Tok->Parent == NULL)
1024 Tok->Type = TT_ObjCMethodSpecifier;
1025 break;
Nico Weberbcfdd262013-01-12 06:18:40 +00001026 case tok::colon:
1027 // Colons from ?: are handled in parseConditional().
Daniel Jasper1f2b0782013-01-16 16:23:19 +00001028 if (Tok->Parent->is(tok::r_paren))
1029 Tok->Type = TT_CtorInitializerColon;
Nico Weberbcfdd262013-01-12 06:18:40 +00001030 if (ColonIsObjCMethodExpr)
1031 Tok->Type = TT_ObjCMethodExpr;
1032 break;
Nico Weber5096a442013-01-17 17:17:19 +00001033 case tok::kw_if:
1034 case tok::kw_while:
1035 if (CurrentToken->is(tok::l_paren)) {
1036 next();
1037 if (!parseParens(/*LookForDecls=*/true))
1038 return false;
1039 }
1040 break;
Nico Weber94fb7292013-01-18 05:50:57 +00001041 case tok::l_paren:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001042 if (!parseParens())
1043 return false;
Nico Weber94fb7292013-01-18 05:50:57 +00001044 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001045 case tok::l_square:
Daniel Jasper1f42f112013-01-04 18:52:56 +00001046 if (!parseSquare())
1047 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001048 break;
Daniel Jasper700e7102013-01-10 09:26:47 +00001049 case tok::l_brace:
1050 if (!parseBrace())
1051 return false;
1052 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001053 case tok::less:
Daniel Jasper20409152012-12-04 14:54:30 +00001054 if (parseAngle())
Daniel Jasper26f7e782013-01-08 14:56:18 +00001055 Tok->Type = TT_TemplateOpener;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001056 else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001057 Tok->Type = TT_BinaryOperator;
1058 CurrentToken = Tok;
1059 next();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001060 }
1061 break;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001062 case tok::r_paren:
1063 case tok::r_square:
1064 return false;
Daniel Jasper700e7102013-01-10 09:26:47 +00001065 case tok::r_brace:
1066 // Lines can start with '}'.
1067 if (Tok->Parent != NULL)
1068 return false;
1069 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001070 case tok::greater:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001071 Tok->Type = TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001072 break;
1073 case tok::kw_operator:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001074 if (CurrentToken->is(tok::l_paren)) {
1075 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001076 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001077 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1078 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001079 next();
1080 }
1081 } else {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001082 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1083 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasperf6aef6a2012-12-24 10:56:04 +00001084 next();
1085 }
1086 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001087 break;
1088 case tok::question:
Daniel Jasper20409152012-12-04 14:54:30 +00001089 parseConditional();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001090 break;
Daniel Jasper9a64fb52013-01-02 15:08:56 +00001091 case tok::kw_template:
1092 parseTemplateDeclaration();
1093 break;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001094 default:
1095 break;
1096 }
Daniel Jasper1f42f112013-01-04 18:52:56 +00001097 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001098 }
1099
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001100 void parseIncludeDirective() {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001101 next();
1102 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1103 next();
1104 while (CurrentToken != NULL) {
Daniel Jasper7d1185d2013-01-18 09:19:33 +00001105 if (CurrentToken->isNot(tok::comment) ||
1106 !CurrentToken->Children.empty())
1107 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001108 next();
1109 }
1110 } else {
1111 while (CurrentToken != NULL) {
1112 next();
1113 }
1114 }
1115 }
1116
1117 void parseWarningOrError() {
1118 next();
1119 // We still want to format the whitespace left of the first token of the
1120 // warning or error.
1121 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001122 while (CurrentToken != NULL) {
Manuel Klimek407a31a2013-01-15 15:50:27 +00001123 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001124 next();
1125 }
1126 }
1127
1128 void parsePreprocessorDirective() {
1129 next();
Daniel Jasper26f7e782013-01-08 14:56:18 +00001130 if (CurrentToken == NULL)
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001131 return;
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001132 // Hashes in the middle of a line can lead to any strange token
1133 // sequence.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001134 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001135 return;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001136 switch (
1137 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001138 case tok::pp_include:
Nico Weberb23ae0c2012-12-21 18:21:56 +00001139 case tok::pp_import:
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001140 parseIncludeDirective();
1141 break;
Manuel Klimek407a31a2013-01-15 15:50:27 +00001142 case tok::pp_error:
1143 case tok::pp_warning:
1144 parseWarningOrError();
1145 break;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001146 default:
1147 break;
1148 }
1149 }
1150
Daniel Jasper71607512013-01-07 10:48:50 +00001151 LineType parseLine() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001152 if (CurrentToken->is(tok::hash)) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001153 parsePreprocessorDirective();
Daniel Jasper71607512013-01-07 10:48:50 +00001154 return LT_PreprocessorDirective;
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001155 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001156 while (CurrentToken != NULL) {
1157 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasper71607512013-01-07 10:48:50 +00001158 KeywordVirtualFound = true;
Daniel Jasper1f42f112013-01-04 18:52:56 +00001159 if (!consumeToken())
Daniel Jasper71607512013-01-07 10:48:50 +00001160 return LT_Invalid;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001161 }
Daniel Jasper71607512013-01-07 10:48:50 +00001162 if (KeywordVirtualFound)
1163 return LT_VirtualFunctionDecl;
1164 return LT_Other;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001165 }
1166
1167 void next() {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001168 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1169 CurrentToken = &CurrentToken->Children[0];
1170 else
1171 CurrentToken = NULL;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001172 }
1173
1174 private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001175 AnnotatedToken *CurrentToken;
Daniel Jasper71607512013-01-07 10:48:50 +00001176 bool KeywordVirtualFound;
Nico Weberbcfdd262013-01-12 06:18:40 +00001177 bool ColonIsObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001178 };
1179
Daniel Jasper26f7e782013-01-08 14:56:18 +00001180 void calculateExtraInformation(AnnotatedToken &Current) {
1181 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1182
Manuel Klimek526ed112013-01-09 15:25:02 +00001183 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001184 Current.MustBreakBefore = true;
1185 } else {
Daniel Jasper487f64b2013-01-13 16:10:20 +00001186 if (Current.Type == TT_LineComment) {
1187 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001188 } else if ((Current.Parent->is(tok::comment) &&
1189 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper487f64b2013-01-13 16:10:20 +00001190 (Current.is(tok::string_literal) &&
1191 Current.Parent->is(tok::string_literal))) {
Manuel Klimek526ed112013-01-09 15:25:02 +00001192 Current.MustBreakBefore = true;
Manuel Klimek526ed112013-01-09 15:25:02 +00001193 } else {
1194 Current.MustBreakBefore = false;
1195 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001196 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001197 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001198 if (Current.MustBreakBefore)
1199 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1200 else
1201 Current.TotalLength = Current.Parent->TotalLength +
1202 Current.FormatTok.TokenLength +
1203 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001204 if (!Current.Children.empty())
1205 calculateExtraInformation(Current.Children[0]);
1206 }
1207
Daniel Jasper995e8202013-01-14 13:08:07 +00001208 void annotate() {
Daniel Jasper995e8202013-01-14 13:08:07 +00001209 AnnotatingParser Parser(Line.First);
1210 Line.Type = Parser.parseLine();
1211 if (Line.Type == LT_Invalid)
1212 return;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001213
Daniel Jasper995e8202013-01-14 13:08:07 +00001214 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasper71607512013-01-07 10:48:50 +00001215
Daniel Jasper995e8202013-01-14 13:08:07 +00001216 if (Line.First.Type == TT_ObjCMethodSpecifier)
1217 Line.Type = LT_ObjCMethodDecl;
1218 else if (Line.First.Type == TT_ObjCDecl)
1219 Line.Type = LT_ObjCDecl;
1220 else if (Line.First.Type == TT_ObjCProperty)
1221 Line.Type = LT_ObjCProperty;
Daniel Jasper71607512013-01-07 10:48:50 +00001222
Daniel Jasper995e8202013-01-14 13:08:07 +00001223 Line.First.SpaceRequiredBefore = true;
1224 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1225 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001226
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001227 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasper995e8202013-01-14 13:08:07 +00001228 if (!Line.First.Children.empty())
1229 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001230 }
1231
1232private:
Daniel Jasper26f7e782013-01-08 14:56:18 +00001233 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1234 if (getPrecedence(Current) == prec::Assignment ||
1235 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1236 IsRHS = true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001237
Daniel Jasper26f7e782013-01-08 14:56:18 +00001238 if (Current.Type == TT_Unknown) {
1239 if (Current.is(tok::star) || Current.is(tok::amp)) {
1240 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasper886568d2013-01-09 08:36:49 +00001241 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1242 Current.is(tok::caret)) {
1243 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001244 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1245 Current.Type = determineIncrementUsage(Current);
1246 } else if (Current.is(tok::exclaim)) {
1247 Current.Type = TT_UnaryOperator;
1248 } else if (isBinaryOperator(Current)) {
1249 Current.Type = TT_BinaryOperator;
1250 } else if (Current.is(tok::comment)) {
1251 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1252 Lex.getLangOpts()));
Manuel Klimek6cf58142013-01-07 08:54:53 +00001253 if (StringRef(Data).startswith("//"))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001254 Current.Type = TT_LineComment;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001255 else
Daniel Jasper26f7e782013-01-08 14:56:18 +00001256 Current.Type = TT_BlockComment;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001257 } else if (Current.is(tok::r_paren) &&
1258 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasper4981bd02013-01-13 08:01:36 +00001259 Current.Parent->Type == TT_TemplateCloser) &&
1260 (Current.Children.empty() ||
1261 (Current.Children[0].isNot(tok::equal) &&
1262 Current.Children[0].isNot(tok::semi) &&
1263 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001264 // FIXME: We need to get smarter and understand more cases of casts.
1265 Current.Type = TT_CastRParen;
Nico Webered91bba2013-01-10 19:19:14 +00001266 } else if (Current.is(tok::at) && Current.Children.size()) {
1267 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1268 case tok::objc_interface:
1269 case tok::objc_implementation:
1270 case tok::objc_protocol:
1271 Current.Type = TT_ObjCDecl;
Nico Weber70848232013-01-10 21:30:42 +00001272 break;
1273 case tok::objc_property:
1274 Current.Type = TT_ObjCProperty;
1275 break;
Nico Webered91bba2013-01-10 19:19:14 +00001276 default:
1277 break;
1278 }
Daniel Jasperbac016b2012-12-03 18:12:45 +00001279 }
1280 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001281
1282 if (!Current.Children.empty())
1283 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001284 }
1285
Daniel Jasper26f7e782013-01-08 14:56:18 +00001286 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001287 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jaspercf225b62012-12-24 13:43:52 +00001288 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001289 }
1290
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001291 /// \brief Returns the previous token ignoring comments.
1292 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1293 const AnnotatedToken *PrevToken = Tok.Parent;
1294 while (PrevToken != NULL && PrevToken->is(tok::comment))
1295 PrevToken = PrevToken->Parent;
1296 return PrevToken;
1297 }
1298
1299 /// \brief Returns the next token ignoring comments.
1300 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1301 if (Tok.Children.empty())
1302 return NULL;
1303 const AnnotatedToken *NextToken = &Tok.Children[0];
1304 while (NextToken->is(tok::comment)) {
1305 if (NextToken->Children.empty())
1306 return NULL;
1307 NextToken = &NextToken->Children[0];
1308 }
1309 return NextToken;
1310 }
1311
1312 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001313 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001314 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1315 if (PrevToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001316 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001317
1318 const AnnotatedToken *NextToken = getNextToken(Tok);
1319 if (NextToken == NULL)
Daniel Jasper71607512013-01-07 10:48:50 +00001320 return TT_Unknown;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001321
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001322 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1323 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1324 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1325 PrevToken->Type == TT_BinaryOperator ||
Daniel Jasper48bd7b72013-01-16 16:04:06 +00001326 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasper71607512013-01-07 10:48:50 +00001327 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001328
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001329 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1330 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1331 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1332 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1333 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1334 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1335 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasper71607512013-01-07 10:48:50 +00001336 return TT_BinaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001337
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001338 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1339 NextToken->is(tok::greater))
Daniel Jasper71607512013-01-07 10:48:50 +00001340 return TT_PointerOrReference;
Daniel Jasperef5b9c32013-01-02 15:46:59 +00001341
Daniel Jasper112fb272012-12-05 07:51:39 +00001342 // It is very unlikely that we are going to find a pointer or reference type
1343 // definition on the RHS of an assignment.
Nico Weber00d5a042012-12-23 01:07:46 +00001344 if (IsRHS)
Daniel Jasper71607512013-01-07 10:48:50 +00001345 return TT_BinaryOperator;
Daniel Jasper112fb272012-12-05 07:51:39 +00001346
Daniel Jasper71607512013-01-07 10:48:50 +00001347 return TT_PointerOrReference;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001348 }
1349
Daniel Jasper886568d2013-01-09 08:36:49 +00001350 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001351 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1352 if (PrevToken == NULL)
1353 return TT_UnaryOperator;
1354
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001355 // Use heuristics to recognize unary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001356 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1357 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1358 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1359 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1360 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasper71607512013-01-07 10:48:50 +00001361 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001362
1363 // There can't be to consecutive binary operators.
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001364 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasper71607512013-01-07 10:48:50 +00001365 return TT_UnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001366
1367 // Fall back to marking the token as binary operator.
Daniel Jasper71607512013-01-07 10:48:50 +00001368 return TT_BinaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001369 }
1370
1371 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper26f7e782013-01-08 14:56:18 +00001372 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001373 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1374 if (PrevToken == NULL)
Daniel Jasper4abbb532013-01-14 12:18:19 +00001375 return TT_UnaryOperator;
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001376 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1377 PrevToken->is(tok::identifier))
Daniel Jasper71607512013-01-07 10:48:50 +00001378 return TT_TrailingUnaryOperator;
Daniel Jasper98e6b4a2012-12-21 09:41:31 +00001379
Daniel Jasper71607512013-01-07 10:48:50 +00001380 return TT_UnaryOperator;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001381 }
1382
Daniel Jasper26f7e782013-01-08 14:56:18 +00001383 bool spaceRequiredBetween(const AnnotatedToken &Left,
1384 const AnnotatedToken &Right) {
Daniel Jasper765561f2013-01-08 16:17:54 +00001385 if (Right.is(tok::hashhash))
1386 return Left.is(tok::hash);
1387 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1388 return Right.is(tok::hash);
Daniel Jasper8b39c662012-12-10 18:59:13 +00001389 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1390 return false;
Nico Weber5f500df2013-01-10 20:12:55 +00001391 if (Right.is(tok::less) &&
1392 (Left.is(tok::kw_template) ||
Daniel Jasper995e8202013-01-14 13:08:07 +00001393 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001394 return true;
1395 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1396 return false;
1397 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1398 return false;
Nico Webercb4d6902013-01-08 19:40:21 +00001399 if (Left.is(tok::at) &&
1400 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1401 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001402 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1403 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian154120c2012-12-20 19:54:13 +00001404 return false;
Daniel Jasper6b825c22013-01-16 07:19:28 +00001405 if (Left.is(tok::coloncolon))
1406 return false;
1407 if (Right.is(tok::coloncolon))
1408 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001409 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1410 return false;
Daniel Jasperc74e2792012-12-07 09:52:15 +00001411 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001412 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasperd7610b82012-12-24 16:51:15 +00001413 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1414 !Style.PointerAndReferenceBindToType);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001415 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper26f7e782013-01-08 14:56:18 +00001416 return Right.FormatTok.Tok.isLiteral() ||
1417 Style.PointerAndReferenceBindToType;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001418 if (Right.is(tok::star) && Left.is(tok::l_paren))
1419 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001420 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1421 return false;
1422 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperbac016b2012-12-03 18:12:45 +00001423 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001424 if (Left.is(tok::period) || Right.is(tok::period))
1425 return false;
Nico Weberbcfdd262013-01-12 06:18:40 +00001426 if (Left.is(tok::colon))
1427 return Left.Type != TT_ObjCMethodExpr;
1428 if (Right.is(tok::colon))
1429 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001430 if (Left.is(tok::l_paren))
1431 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001432 if (Right.is(tok::l_paren)) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001433 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Webered91bba2013-01-10 19:19:14 +00001434 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001435 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasper088dab52013-01-11 16:09:04 +00001436 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1437 Left.is(tok::kw_delete);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001438 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001439 if (Left.is(tok::at) &&
1440 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Weberd0af4b42013-01-07 16:14:28 +00001441 return false;
Manuel Klimek36fab8d2013-01-10 13:24:24 +00001442 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1443 return false;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001444 return true;
1445 }
1446
Daniel Jasper26f7e782013-01-08 14:56:18 +00001447 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001448 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001449 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1450 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001451 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001452 if (Tok.is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001453 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001454 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weberaab60052013-01-17 06:14:50 +00001455 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001456 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001457 // Don't space between ')' and <id>
1458 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001459 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001460 // Don't space between ':' and '('
1461 return false;
1462 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001463 if (Line.Type == LT_ObjCProperty &&
Nico Weber70848232013-01-10 21:30:42 +00001464 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1465 return false;
Daniel Jasperda927712013-01-07 15:36:15 +00001466
Daniel Jasper4e9008a2013-01-13 08:19:51 +00001467 if (Tok.Parent->is(tok::comma))
1468 return true;
Daniel Jasper46ef8522013-01-10 13:08:12 +00001469 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001470 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001471 if (Tok.Type == TT_OverloadedOperator)
1472 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasper46ef8522013-01-10 13:08:12 +00001473 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001474 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001475 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001476 if (Tok.is(tok::colon))
Daniel Jasper995e8202013-01-14 13:08:07 +00001477 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Weberbcfdd262013-01-12 06:18:40 +00001478 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper5cf7cf32013-01-10 11:14:08 +00001479 if (Tok.Parent->Type == TT_UnaryOperator ||
1480 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperda927712013-01-07 15:36:15 +00001481 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001482 if (Tok.Type == TT_UnaryOperator)
1483 return Tok.Parent->isNot(tok::l_paren) &&
Nico Webercd458332013-01-12 23:48:49 +00001484 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1485 (Tok.Parent->isNot(tok::colon) ||
1486 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper26f7e782013-01-08 14:56:18 +00001487 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1488 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperda927712013-01-07 15:36:15 +00001489 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1490 }
Daniel Jasper26f7e782013-01-08 14:56:18 +00001491 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001492 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001493 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperda927712013-01-07 15:36:15 +00001494 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001495 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperda927712013-01-07 15:36:15 +00001496 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001497 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperda927712013-01-07 15:36:15 +00001498 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001499 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperda927712013-01-07 15:36:15 +00001500 }
1501
Daniel Jasper26f7e782013-01-08 14:56:18 +00001502 bool canBreakBefore(const AnnotatedToken &Right) {
1503 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasper995e8202013-01-14 13:08:07 +00001504 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper26f7e782013-01-08 14:56:18 +00001505 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1506 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperda927712013-01-07 15:36:15 +00001507 return true;
Nico Weber774b9732013-01-12 07:00:16 +00001508 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1509 Left.Parent->is(tok::colon))
Daniel Jasperda927712013-01-07 15:36:15 +00001510 // Don't break this identifier as ':' or identifier
1511 // before it will break.
1512 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001513 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1514 Left.CanBreakBefore)
Daniel Jasperda927712013-01-07 15:36:15 +00001515 // Don't break at ':' if identifier before it can beak.
1516 return false;
1517 }
Nico Weberbcfdd262013-01-12 06:18:40 +00001518 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1519 return false;
1520 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1521 return true;
Nico Webere8ccc812013-01-12 22:48:47 +00001522 if (isObjCSelectorName(Right))
1523 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001524 if (Left.ClosesTemplateDeclaration)
Daniel Jasper5eda31e2013-01-02 18:30:06 +00001525 return true;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001526 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper2db356d2013-01-08 20:03:18 +00001527 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasper4dc41de2013-01-02 08:44:14 +00001528 return false;
Daniel Jasper995e8202013-01-14 13:08:07 +00001529 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasper71607512013-01-07 10:48:50 +00001530 return false;
1531
Daniel Jasper2c6cc482013-01-17 12:53:34 +00001532 if (Right.Type == TT_LineComment)
Daniel Jasper487f64b2013-01-13 16:10:20 +00001533 // We rely on MustBreakBefore being set correctly here as we should not
1534 // change the "binding" behavior of a comment.
1535 return false;
1536
Daniel Jasper60ca75d2013-01-17 13:31:52 +00001537 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1538 // unless it is follow by ';', '{' or '='.
1539 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1540 Left.Parent->is(tok::r_paren))
1541 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1542 Right.isNot(tok::equal);
1543
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001544 // We only break before r_brace if there was a corresponding break before
1545 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1546 if (Right.is(tok::r_brace))
1547 return false;
1548
Daniel Jasperb369c2c2013-01-15 14:27:39 +00001549 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperbac016b2012-12-03 18:12:45 +00001550 return false;
Daniel Jasper26f7e782013-01-08 14:56:18 +00001551 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1552 Left.is(tok::comma) || Right.is(tok::lessless) ||
1553 Right.is(tok::arrow) || Right.is(tok::period) ||
1554 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimek2c7739e2013-01-14 16:41:43 +00001555 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1556 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1557 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper26f7e782013-01-08 14:56:18 +00001558 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001559 }
1560
Daniel Jasperbac016b2012-12-03 18:12:45 +00001561 FormatStyle Style;
1562 SourceManager &SourceMgr;
Manuel Klimek6cf58142013-01-07 08:54:53 +00001563 Lexer &Lex;
Daniel Jasper995e8202013-01-14 13:08:07 +00001564 AnnotatedLine &Line;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001565};
1566
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001567class LexerBasedFormatTokenSource : public FormatTokenSource {
1568public:
1569 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper1321eb52012-12-18 21:05:13 +00001570 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001571 IdentTable(Lex.getLangOpts()) {
1572 Lex.SetKeepWhitespaceMode(true);
1573 }
1574
1575 virtual FormatToken getNextToken() {
1576 if (GreaterStashed) {
1577 FormatTok.NewlinesBefore = 0;
1578 FormatTok.WhiteSpaceStart =
1579 FormatTok.Tok.getLocation().getLocWithOffset(1);
1580 FormatTok.WhiteSpaceLength = 0;
1581 GreaterStashed = false;
1582 return FormatTok;
1583 }
1584
1585 FormatTok = FormatToken();
1586 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001587 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001588 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimekf6fd00b2013-01-05 22:56:06 +00001589 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1590 FormatTok.IsFirst = true;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001591
1592 // Consume and record whitespace until we find a significant token.
1593 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka080a182013-01-02 16:30:12 +00001594 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jaspercd162382013-01-07 13:26:07 +00001595 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1596 FormatTok.NewlinesBefore;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001597 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1598
1599 if (FormatTok.Tok.is(tok::eof))
1600 return FormatTok;
1601 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimek95419382013-01-07 07:56:50 +00001602 Text = rawTokenText(FormatTok.Tok);
Manuel Klimekd4397b92013-01-04 23:34:14 +00001603 }
Manuel Klimek95419382013-01-07 07:56:50 +00001604
1605 // Now FormatTok is the next non-whitespace token.
1606 FormatTok.TokenLength = Text.size();
1607
Manuel Klimekd4397b92013-01-04 23:34:14 +00001608 // In case the token starts with escaped newlines, we want to
1609 // take them into account as whitespace - this pattern is quite frequent
1610 // in macro definitions.
1611 // FIXME: What do we want to do with other escaped spaces, and escaped
1612 // spaces or newlines in the middle of tokens?
1613 // FIXME: Add a more explicit test.
1614 unsigned i = 0;
Daniel Jasper71607512013-01-07 10:48:50 +00001615 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001616 FormatTok.WhiteSpaceLength += 2;
Manuel Klimek95419382013-01-07 07:56:50 +00001617 FormatTok.TokenLength -= 2;
Manuel Klimekd4397b92013-01-04 23:34:14 +00001618 i += 2;
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001619 }
1620
1621 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimekd4397b92013-01-04 23:34:14 +00001622 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jaspercd1a32b2012-12-21 17:58:39 +00001623 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001624 FormatTok.Tok.setKind(Info.getTokenID());
1625 }
1626
1627 if (FormatTok.Tok.is(tok::greatergreater)) {
1628 FormatTok.Tok.setKind(tok::greater);
1629 GreaterStashed = true;
1630 }
1631
1632 return FormatTok;
1633 }
1634
1635private:
1636 FormatToken FormatTok;
1637 bool GreaterStashed;
1638 Lexer &Lex;
1639 SourceManager &SourceMgr;
1640 IdentifierTable IdentTable;
1641
1642 /// Returns the text of \c FormatTok.
Manuel Klimek95419382013-01-07 07:56:50 +00001643 StringRef rawTokenText(Token &Tok) {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001644 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1645 Tok.getLength());
1646 }
1647};
1648
Daniel Jasperbac016b2012-12-03 18:12:45 +00001649class Formatter : public UnwrappedLineConsumer {
1650public:
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001651 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1652 SourceManager &SourceMgr,
Daniel Jasperbac016b2012-12-03 18:12:45 +00001653 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001654 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001655 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperbac016b2012-12-03 18:12:45 +00001656
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001657 virtual ~Formatter() {}
Daniel Jasperaccb0b02012-12-04 21:05:31 +00001658
Daniel Jasperbac016b2012-12-03 18:12:45 +00001659 tooling::Replacements format() {
Alexander Kornienko469a21b2012-12-07 16:15:44 +00001660 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001661 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001662 StructuralError = Parser.parse();
Manuel Klimekd4397b92013-01-04 23:34:14 +00001663 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasper995e8202013-01-14 13:08:07 +00001664 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1665 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1666 Annotator.annotate();
1667 }
1668 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1669 E = AnnotatedLines.end();
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001670 I != E; ++I) {
Daniel Jasper995e8202013-01-14 13:08:07 +00001671 const AnnotatedLine &TheLine = *I;
1672 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1673 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1674 TheLine.InPPDirective,
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001675 PreviousEndOfLineColumn);
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001676 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasper995e8202013-01-14 13:08:07 +00001677 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001678 TheLine.First, Whitespaces,
Daniel Jasper995e8202013-01-14 13:08:07 +00001679 StructuralError);
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001680 PreviousEndOfLineColumn = Formatter.format();
1681 } else {
1682 // If we did not reformat this unwrapped line, the column at the end of
1683 // the last token is unchanged - thus, we can calculate the end of the
1684 // last token, and return the result.
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001685 PreviousEndOfLineColumn =
Daniel Jasper995e8202013-01-14 13:08:07 +00001686 SourceMgr.getSpellingColumnNumber(
1687 TheLine.Last->FormatTok.Tok.getLocation()) +
1688 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1689 SourceMgr, Lex.getLangOpts()) -
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001690 1;
1691 }
1692 }
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001693 return Whitespaces.generateReplacements();
Daniel Jasperbac016b2012-12-03 18:12:45 +00001694 }
1695
1696private:
Manuel Klimek517e8942013-01-11 17:54:10 +00001697 /// \brief Tries to merge lines into one.
1698 ///
1699 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1700 /// if possible; note that \c I will be incremented when lines are merged.
1701 ///
1702 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001703 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasper995e8202013-01-14 13:08:07 +00001704 std::vector<AnnotatedLine>::iterator &I,
1705 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimek517e8942013-01-11 17:54:10 +00001706 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1707
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001708 // We can never merge stuff if there are trailing line comments.
1709 if (I->Last->Type == TT_LineComment)
1710 return;
1711
Manuel Klimek517e8942013-01-11 17:54:10 +00001712 // Check whether the UnwrappedLine can be put onto a single line. If
1713 // so, this is bound to be the optimal solution (by definition) and we
1714 // don't need to analyze the entire solution space.
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001715 if (I->Last->TotalLength >= Limit)
1716 return;
1717 Limit -= I->Last->TotalLength + 1; // One space.
Daniel Jasper55b08e72013-01-16 07:02:34 +00001718
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001719 if (I + 1 == E)
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001720 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001721
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001722 if (I->Last->is(tok::l_brace)) {
1723 tryMergeSimpleBlock(I, E, Limit);
1724 } else if (I->First.is(tok::kw_if)) {
1725 tryMergeSimpleIf(I, E, Limit);
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001726 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1727 I->First.FormatTok.IsFirst)) {
1728 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001729 }
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001730 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001731 }
1732
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001733 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1734 std::vector<AnnotatedLine>::iterator E,
1735 unsigned Limit) {
1736 AnnotatedLine &Line = *I;
Daniel Jasper2b9c10b2013-01-14 15:52:06 +00001737 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1738 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001739 if (I + 2 != E && (I + 2)->InPPDirective &&
1740 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1741 return;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001742 if ((I + 1)->Last->TotalLength > Limit)
1743 return;
Daniel Jaspere0b15ea2013-01-14 15:40:57 +00001744 join(Line, *(++I));
1745 }
1746
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001747 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1748 std::vector<AnnotatedLine>::iterator E,
1749 unsigned Limit) {
Daniel Jasper6f5bb2c2013-01-14 16:24:39 +00001750 if (!Style.AllowShortIfStatementsOnASingleLine)
1751 return;
Manuel Klimek4c128122013-01-18 14:46:43 +00001752 if ((I + 1)->InPPDirective != I->InPPDirective ||
1753 ((I + 1)->InPPDirective &&
1754 (I + 1)->First.FormatTok.HasUnescapedNewline))
1755 return;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001756 AnnotatedLine &Line = *I;
Daniel Jasper55b08e72013-01-16 07:02:34 +00001757 if (Line.Last->isNot(tok::r_paren))
1758 return;
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001759 if ((I + 1)->Last->TotalLength > Limit)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001760 return;
1761 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1762 return;
1763 // Only inline simple if's (no nested if or else).
1764 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1765 return;
1766 join(Line, *(++I));
1767 }
1768
1769 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1770 std::vector<AnnotatedLine>::iterator E,
1771 unsigned Limit){
Daniel Jasper995e8202013-01-14 13:08:07 +00001772 // Check that we still have three lines and they fit into the limit.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001773 if (I + 2 == E || !nextTwoLinesFitInto(I, Limit))
1774 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001775
1776 // First, check that the current line allows merging. This is the case if
1777 // we're not in a control flow statement and the last token is an opening
1778 // brace.
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001779 AnnotatedLine &Line = *I;
Manuel Klimek517e8942013-01-11 17:54:10 +00001780 bool AllowedTokens =
Daniel Jasper995e8202013-01-14 13:08:07 +00001781 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1782 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1783 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1784 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Weber67015ed2013-01-11 21:14:08 +00001785 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasper995e8202013-01-14 13:08:07 +00001786 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1787 Line.First.isNot(tok::plus);
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001788 if (!AllowedTokens)
1789 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001790
1791 // Second, check that the next line does not contain any braces - if it
1792 // does, readability declines when putting it into a single line.
Daniel Jasper995e8202013-01-14 13:08:07 +00001793 const AnnotatedToken *Tok = &(I + 1)->First;
1794 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001795 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001796 do {
1797 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001798 return;
Daniel Jasper995e8202013-01-14 13:08:07 +00001799 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1800 } while (Tok != NULL);
Manuel Klimek517e8942013-01-11 17:54:10 +00001801
1802 // Last, check that the third line contains a single closing brace.
Daniel Jasper995e8202013-01-14 13:08:07 +00001803 Tok = &(I + 2)->First;
1804 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1805 Tok->MustBreakBefore)
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001806 return;
Manuel Klimek517e8942013-01-11 17:54:10 +00001807
Daniel Jasper995e8202013-01-14 13:08:07 +00001808 // If the merged line fits, we use that instead and skip the next two lines.
1809 Line.Last->Children.push_back((I + 1)->First);
1810 while (!Line.Last->Children.empty()) {
1811 Line.Last->Children[0].Parent = Line.Last;
1812 Line.Last = &Line.Last->Children[0];
Manuel Klimek517e8942013-01-11 17:54:10 +00001813 }
Daniel Jasper995e8202013-01-14 13:08:07 +00001814
1815 join(Line, *(I + 1));
1816 join(Line, *(I + 2));
1817 I += 2;
Daniel Jasperfeb18f52013-01-14 14:14:23 +00001818 }
1819
1820 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1821 unsigned Limit) {
Daniel Jasper3f8cdbf2013-01-16 10:41:46 +00001822 return (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= Limit;
Manuel Klimek517e8942013-01-11 17:54:10 +00001823 }
1824
Daniel Jasper995e8202013-01-14 13:08:07 +00001825 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1826 A.Last->Children.push_back(B.First);
1827 while (!A.Last->Children.empty()) {
1828 A.Last->Children[0].Parent = A.Last;
1829 A.Last = &A.Last->Children[0];
1830 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001831 }
1832
Daniel Jasper995e8202013-01-14 13:08:07 +00001833 bool touchesRanges(const AnnotatedLine &TheLine) {
1834 const FormatToken *First = &TheLine.First.FormatTok;
1835 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jaspercd162382013-01-07 13:26:07 +00001836 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper26f7e782013-01-08 14:56:18 +00001837 First->Tok.getLocation(),
1838 Last->Tok.getLocation());
Daniel Jasperbac016b2012-12-03 18:12:45 +00001839 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001840 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1841 Ranges[i].getBegin()) &&
1842 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1843 LineRange.getBegin()))
1844 return true;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001845 }
Manuel Klimekf9ea2ed2013-01-10 19:49:59 +00001846 return false;
1847 }
1848
1849 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jaspercbb6c412013-01-16 09:10:19 +00001850 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperbac016b2012-12-03 18:12:45 +00001851 }
1852
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001853 /// \brief Add a new line and the required indent before the first Token
1854 /// of the \c UnwrappedLine if there was no structural parsing error.
1855 /// Returns the indent level of the \c UnwrappedLine.
1856 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1857 bool InPPDirective,
1858 unsigned PreviousEndOfLineColumn) {
Daniel Jasper7d19bc22013-01-11 14:23:32 +00001859 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001860 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1861 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1862
1863 unsigned Newlines = std::min(Tok.NewlinesBefore,
1864 Style.MaxEmptyLinesToKeep + 1);
1865 if (Newlines == 0 && !Tok.IsFirst)
1866 Newlines = 1;
1867 unsigned Indent = Level * 2;
1868
1869 bool IsAccessModifier = false;
1870 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1871 RootToken.is(tok::kw_private))
1872 IsAccessModifier = true;
1873 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1874 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1875 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1876 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1877 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1878 IsAccessModifier = true;
1879
1880 if (IsAccessModifier &&
1881 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1882 Indent += Style.AccessModifierOffset;
1883 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001884 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001885 } else {
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001886 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1887 PreviousEndOfLineColumn, Style);
Manuel Klimek3f8c7f32013-01-10 18:45:26 +00001888 }
1889 return Indent;
1890 }
1891
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001892 DiagnosticsEngine &Diag;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001893 FormatStyle Style;
1894 Lexer &Lex;
1895 SourceManager &SourceMgr;
Daniel Jasperdcc2a622013-01-18 08:44:07 +00001896 WhitespaceManager Whitespaces;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001897 std::vector<CharSourceRange> Ranges;
Daniel Jasper995e8202013-01-14 13:08:07 +00001898 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienkocff563c2012-12-04 17:27:50 +00001899 bool StructuralError;
Daniel Jasperbac016b2012-12-03 18:12:45 +00001900};
1901
1902tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1903 SourceManager &SourceMgr,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001904 std::vector<CharSourceRange> Ranges,
1905 DiagnosticConsumer *DiagClient) {
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001906 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001907 OwningPtr<DiagnosticConsumer> DiagPrinter;
1908 if (DiagClient == 0) {
1909 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1910 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1911 DiagClient = DiagPrinter.get();
1912 }
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001913 DiagnosticsEngine Diagnostics(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001914 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienkoa4ae9f32013-01-14 11:34:14 +00001915 DiagClient, false);
Alexander Kornienko3048aea2013-01-10 15:05:09 +00001916 Diagnostics.setSourceManager(&SourceMgr);
1917 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperbac016b2012-12-03 18:12:45 +00001918 return formatter.format();
1919}
1920
Daniel Jasper46ef8522013-01-10 13:08:12 +00001921LangOptions getFormattingLangOpts() {
1922 LangOptions LangOpts;
1923 LangOpts.CPlusPlus = 1;
1924 LangOpts.CPlusPlus11 = 1;
1925 LangOpts.Bool = 1;
1926 LangOpts.ObjC1 = 1;
1927 LangOpts.ObjC2 = 1;
1928 return LangOpts;
1929}
1930
Daniel Jaspercd162382013-01-07 13:26:07 +00001931} // namespace format
1932} // namespace clang