blob: 05c96bd38da75d6c8bd0a0d0d3b070b59e9371bb [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- Format.cpp - Format C++ code -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements functions declared in Format.h. This will be
12/// split into separate files as we go.
13///
14/// This is EXPERIMENTAL code under heavy development. It is not in a state yet,
15/// where it can be used to format real code.
16///
17//===----------------------------------------------------------------------===//
18
Manuel Klimek24998102013-01-16 14:55:28 +000019#define DEBUG_TYPE "format-formatter"
20
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "UnwrappedLineParser.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000022#include "clang/Basic/Diagnostic.h"
Daniel Jasperab7654e2012-12-21 10:20:02 +000023#include "clang/Basic/OperatorPrecedence.h"
Chandler Carruth44eb4f62013-01-02 10:28:36 +000024#include "clang/Basic/SourceManager.h"
Manuel Klimek24998102013-01-16 14:55:28 +000025#include "clang/Format/Format.h"
Alexander Kornienko5b7157a2013-01-10 15:05:09 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000027#include "clang/Lex/Lexer.h"
Manuel Klimek24998102013-01-16 14:55:28 +000028#include "llvm/Support/Debug.h"
Daniel Jasper8b529712012-12-04 13:02:32 +000029#include <string>
30
Manuel Klimek24998102013-01-16 14:55:28 +000031// Uncomment to get debug output from tests:
32// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
33
Daniel Jasperf7935112012-12-03 18:12:45 +000034namespace clang {
35namespace format {
36
Daniel Jasperda16db32013-01-07 10:48:50 +000037enum TokenType {
Daniel Jasperda16db32013-01-07 10:48:50 +000038 TT_BinaryOperator,
Daniel Jasper7194e182013-01-10 11:14:08 +000039 TT_BlockComment,
40 TT_CastRParen,
Daniel Jasperda16db32013-01-07 10:48:50 +000041 TT_ConditionalExpr,
42 TT_CtorInitializerColon,
Manuel Klimek99c7baa2013-01-15 15:50:27 +000043 TT_ImplicitStringLiteral,
Daniel Jasper7194e182013-01-10 11:14:08 +000044 TT_LineComment,
Daniel Jasperc1fa2812013-01-10 13:08:12 +000045 TT_ObjCBlockLParen,
Nico Weber2bb00742013-01-10 19:19:14 +000046 TT_ObjCDecl,
Daniel Jasper7194e182013-01-10 11:14:08 +000047 TT_ObjCMethodSpecifier,
Nico Webera7252d82013-01-12 06:18:40 +000048 TT_ObjCMethodExpr,
Nico Webera2a84952013-01-10 21:30:42 +000049 TT_ObjCProperty,
Daniel Jasper7194e182013-01-10 11:14:08 +000050 TT_OverloadedOperator,
51 TT_PointerOrReference,
Daniel Jasperda16db32013-01-07 10:48:50 +000052 TT_PureVirtualSpecifier,
Daniel Jasper7194e182013-01-10 11:14:08 +000053 TT_TemplateCloser,
54 TT_TemplateOpener,
55 TT_TrailingUnaryOperator,
56 TT_UnaryOperator,
57 TT_Unknown
Daniel Jasperda16db32013-01-07 10:48:50 +000058};
59
60enum LineType {
61 LT_Invalid,
62 LT_Other,
63 LT_PreprocessorDirective,
64 LT_VirtualFunctionDecl,
Nico Weber2bb00742013-01-10 19:19:14 +000065 LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
Nico Webera2a84952013-01-10 21:30:42 +000066 LT_ObjCMethodDecl,
67 LT_ObjCProperty // An @property line.
Daniel Jasperda16db32013-01-07 10:48:50 +000068};
69
Daniel Jasper7c85fde2013-01-08 14:56:18 +000070class AnnotatedToken {
71public:
Daniel Jasperaa701fa2013-01-18 08:44:07 +000072 explicit AnnotatedToken(const FormatToken &FormatTok)
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +000073 : FormatTok(FormatTok), Type(TT_Unknown), SpaceRequiredBefore(false),
74 CanBreakBefore(false), MustBreakBefore(false),
Daniel Jasper9278eb92013-01-16 14:59:02 +000075 ClosesTemplateDeclaration(false), MatchingParen(NULL), Parent(NULL) {}
Daniel Jasper7c85fde2013-01-08 14:56:18 +000076
Daniel Jasper25837aa2013-01-14 14:14:23 +000077 bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
78 bool isNot(tok::TokenKind Kind) const { return FormatTok.Tok.isNot(Kind); }
79
Daniel Jasper7c85fde2013-01-08 14:56:18 +000080 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
81 return FormatTok.Tok.isObjCAtKeyword(Kind);
82 }
83
84 FormatToken FormatTok;
85
Daniel Jasperf7935112012-12-03 18:12:45 +000086 TokenType Type;
87
Daniel Jasperf7935112012-12-03 18:12:45 +000088 bool SpaceRequiredBefore;
89 bool CanBreakBefore;
90 bool MustBreakBefore;
Daniel Jasperac5c1c22013-01-02 15:08:56 +000091
92 bool ClosesTemplateDeclaration;
Daniel Jasper7c85fde2013-01-08 14:56:18 +000093
Daniel Jasper9278eb92013-01-16 14:59:02 +000094 AnnotatedToken *MatchingParen;
95
Daniel Jaspera67a8f02013-01-16 10:41:46 +000096 /// \brief The total length of the line up to and including this token.
97 unsigned TotalLength;
98
Daniel Jasper7c85fde2013-01-08 14:56:18 +000099 std::vector<AnnotatedToken> Children;
100 AnnotatedToken *Parent;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000101
102 const AnnotatedToken *getPreviousNoneComment() const {
103 AnnotatedToken *Tok = Parent;
104 while (Tok != NULL && Tok->is(tok::comment))
105 Tok = Tok->Parent;
106 return Tok;
107 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000108};
109
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000110class AnnotatedLine {
111public:
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000112 AnnotatedLine(const UnwrappedLine &Line)
113 : First(Line.Tokens.front()), Level(Line.Level),
114 InPPDirective(Line.InPPDirective) {
115 assert(!Line.Tokens.empty());
116 AnnotatedToken *Current = &First;
117 for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
118 E = Line.Tokens.end();
119 I != E; ++I) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000120 Current->Children.push_back(AnnotatedToken(*I));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000121 Current->Children[0].Parent = Current;
122 Current = &Current->Children[0];
123 }
124 Last = Current;
125 }
126 AnnotatedLine(const AnnotatedLine &Other)
127 : First(Other.First), Type(Other.Type), Level(Other.Level),
128 InPPDirective(Other.InPPDirective) {
129 Last = &First;
130 while (!Last->Children.empty()) {
131 Last->Children[0].Parent = Last;
132 Last = &Last->Children[0];
133 }
134 }
135
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000136 AnnotatedToken First;
137 AnnotatedToken *Last;
138
139 LineType Type;
140 unsigned Level;
141 bool InPPDirective;
142};
143
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000144static prec::Level getPrecedence(const AnnotatedToken &Tok) {
145 return getBinOpPrecedence(Tok.FormatTok.Tok.getKind(), true, true);
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000146}
147
Daniel Jasperf7935112012-12-03 18:12:45 +0000148FormatStyle getLLVMStyle() {
149 FormatStyle LLVMStyle;
150 LLVMStyle.ColumnLimit = 80;
151 LLVMStyle.MaxEmptyLinesToKeep = 1;
152 LLVMStyle.PointerAndReferenceBindToType = false;
153 LLVMStyle.AccessModifierOffset = -2;
154 LLVMStyle.SplitTemplateClosingGreater = true;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000155 LLVMStyle.IndentCaseLabels = false;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000156 LLVMStyle.SpacesBeforeTrailingComments = 1;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000157 LLVMStyle.BinPackParameters = true;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000158 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000159 LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000160 LLVMStyle.ObjCSpaceBeforeProtocolList = true;
Daniel Jasperf7935112012-12-03 18:12:45 +0000161 return LLVMStyle;
162}
163
164FormatStyle getGoogleStyle() {
165 FormatStyle GoogleStyle;
166 GoogleStyle.ColumnLimit = 80;
167 GoogleStyle.MaxEmptyLinesToKeep = 1;
168 GoogleStyle.PointerAndReferenceBindToType = true;
169 GoogleStyle.AccessModifierOffset = -1;
170 GoogleStyle.SplitTemplateClosingGreater = false;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000171 GoogleStyle.IndentCaseLabels = true;
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000172 GoogleStyle.SpacesBeforeTrailingComments = 2;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000173 GoogleStyle.BinPackParameters = false;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000174 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
Daniel Jasperced17f82013-01-16 15:44:34 +0000175 GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
Nico Webera6087752013-01-10 20:12:55 +0000176 GoogleStyle.ObjCSpaceBeforeProtocolList = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000177 return GoogleStyle;
178}
179
Daniel Jasper1b750ed2013-01-14 16:24:39 +0000180FormatStyle getChromiumStyle() {
181 FormatStyle ChromiumStyle = getGoogleStyle();
182 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
183 return ChromiumStyle;
184}
185
Daniel Jasperf7935112012-12-03 18:12:45 +0000186struct OptimizationParameters {
Daniel Jasperf7935112012-12-03 18:12:45 +0000187 unsigned PenaltyIndentLevel;
Daniel Jasper6d822722012-12-24 16:43:00 +0000188 unsigned PenaltyLevelDecrease;
Daniel Jasper2df93312013-01-09 10:16:05 +0000189 unsigned PenaltyExcessCharacter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000190};
191
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000192/// \brief Manages the whitespaces around tokens and their replacements.
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000193///
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000194/// This includes special handling for certain constructs, e.g. the alignment of
195/// trailing line comments.
196class WhitespaceManager {
197public:
198 WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
199
200 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
201 /// each \c AnnotatedToken.
202 void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
203 unsigned Spaces, unsigned WhitespaceStartColumn,
204 const FormatStyle &Style) {
Daniel Jasper304a9862013-01-21 22:49:20 +0000205 // 2+ newlines mean an empty line separating logic scopes.
206 if (NewLines >= 2)
207 alignComments();
208
209 // Align line comments if they are trailing or if they continue other
210 // trailing comments.
211 if (Tok.Type == TT_LineComment &&
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000212 (Tok.Parent != NULL || !Comments.empty())) {
213 if (Style.ColumnLimit >=
214 Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) {
215 Comments.push_back(StoredComment());
216 Comments.back().Tok = Tok.FormatTok;
217 Comments.back().Spaces = Spaces;
218 Comments.back().NewLines = NewLines;
219 Comments.back().MinColumn = WhitespaceStartColumn + Spaces;
220 Comments.back().MaxColumn = Style.ColumnLimit -
221 Spaces - Tok.FormatTok.TokenLength;
222 return;
223 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000224 }
Daniel Jasper304a9862013-01-21 22:49:20 +0000225
226 // If this line does not have a trailing comment, align the stored comments.
227 if (Tok.Children.empty() && Tok.Type != TT_LineComment)
228 alignComments();
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000229 storeReplacement(Tok.FormatTok,
230 std::string(NewLines, '\n') + std::string(Spaces, ' '));
231 }
232
233 /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
234 /// backslashes to escape newlines inside a preprocessor directive.
235 ///
236 /// This function and \c replaceWhitespace have the same behavior if
237 /// \c Newlines == 0.
238 void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
239 unsigned Spaces, unsigned WhitespaceStartColumn,
240 const FormatStyle &Style) {
241 std::string NewLineText;
242 if (NewLines > 0) {
243 unsigned Offset = std::min<int>(Style.ColumnLimit - 1,
244 WhitespaceStartColumn);
245 for (unsigned i = 0; i < NewLines; ++i) {
246 NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
247 NewLineText += "\\\n";
248 Offset = 0;
249 }
250 }
251 storeReplacement(Tok.FormatTok, NewLineText + std::string(Spaces, ' '));
252 }
253
254 /// \brief Returns all the \c Replacements created during formatting.
255 const tooling::Replacements &generateReplacements() {
256 alignComments();
257 return Replaces;
258 }
259
260private:
261 /// \brief Structure to store a comment for later layout and alignment.
262 struct StoredComment {
263 FormatToken Tok;
264 unsigned MinColumn;
265 unsigned MaxColumn;
266 unsigned NewLines;
267 unsigned Spaces;
268 };
269 SmallVector<StoredComment, 16> Comments;
270 typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
271
272 /// \brief Try to align all stashed comments.
273 void alignComments() {
274 unsigned MinColumn = 0;
275 unsigned MaxColumn = UINT_MAX;
276 comment_iterator Start = Comments.begin();
277 for (comment_iterator I = Comments.begin(), E = Comments.end(); I != E;
278 ++I) {
279 if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
280 alignComments(Start, I, MinColumn);
281 MinColumn = I->MinColumn;
282 MaxColumn = I->MaxColumn;
283 Start = I;
284 } else {
285 MinColumn = std::max(MinColumn, I->MinColumn);
286 MaxColumn = std::min(MaxColumn, I->MaxColumn);
287 }
288 }
289 alignComments(Start, Comments.end(), MinColumn);
290 Comments.clear();
291 }
292
293 /// \brief Put all the comments between \p I and \p E into \p Column.
294 void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
295 while (I != E) {
296 unsigned Spaces = I->Spaces + Column - I->MinColumn;
297 storeReplacement(I->Tok, std::string(I->NewLines, '\n') +
298 std::string(Spaces, ' '));
299 ++I;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000300 }
301 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000302
303 /// \brief Stores \p Text as the replacement for the whitespace in front of
304 /// \p Tok.
305 void storeReplacement(const FormatToken &Tok, const std::string Text) {
306 Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
307 Tok.WhiteSpaceLength, Text));
308 }
309
310 SourceManager &SourceMgr;
311 tooling::Replacements Replaces;
312};
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000313
Nico Weberc9d73612013-01-12 22:48:47 +0000314/// \brief Returns if a token is an Objective-C selector name.
315///
Nico Weber92c05392013-01-12 22:51:13 +0000316/// For example, "bar" is a selector name in [foo bar:(4 + 5)].
Nico Weberc9d73612013-01-12 22:48:47 +0000317static bool isObjCSelectorName(const AnnotatedToken &Tok) {
318 return Tok.is(tok::identifier) && !Tok.Children.empty() &&
319 Tok.Children[0].is(tok::colon) &&
320 Tok.Children[0].Type == TT_ObjCMethodExpr;
321}
322
Daniel Jasperf7935112012-12-03 18:12:45 +0000323class UnwrappedLineFormatter {
324public:
Manuel Klimekb2c6dbe2013-01-10 19:17:33 +0000325 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000326 const AnnotatedLine &Line, unsigned FirstIndent,
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000327 const AnnotatedToken &RootToken,
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000328 WhitespaceManager &Whitespaces, bool StructuralError)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000329 : Style(Style), SourceMgr(SourceMgr), Line(Line),
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000330 FirstIndent(FirstIndent), RootToken(RootToken),
331 Whitespaces(Whitespaces) {
Daniel Jasper04468962013-01-18 10:56:38 +0000332 Parameters.PenaltyIndentLevel = 20;
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000333 Parameters.PenaltyLevelDecrease = 30;
Daniel Jasper2df93312013-01-09 10:16:05 +0000334 Parameters.PenaltyExcessCharacter = 1000000;
Daniel Jasperf7935112012-12-03 18:12:45 +0000335 }
336
Manuel Klimek1abf7892013-01-04 23:34:14 +0000337 /// \brief Formats an \c UnwrappedLine.
338 ///
339 /// \returns The column after the last token in the last line of the
340 /// \c UnwrappedLine.
341 unsigned format() {
Daniel Jaspere9de2602012-12-06 09:56:08 +0000342 // Initialize state dependent on indent.
Daniel Jasper337816e2013-01-11 10:22:12 +0000343 LineState State;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000344 State.Column = FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000345 State.NextToken = &RootToken;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000346 State.Stack.push_back(ParenState(FirstIndent + 4, FirstIndent));
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000347 State.ForLoopVariablePos = 0;
348 State.LineContainsContinuedForLoopSection = false;
Daniel Jasper6d822722012-12-24 16:43:00 +0000349 State.StartOfLineLevel = 1;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000350
Manuel Klimek24998102013-01-16 14:55:28 +0000351 DEBUG({
352 DebugTokenState(*State.NextToken);
353 });
354
Daniel Jaspere9de2602012-12-06 09:56:08 +0000355 // The first token has already been indented and thus consumed.
356 moveStateToNextToken(State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000357
358 // Start iterating at 1 as we have correctly formatted of Token #0 above.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000359 while (State.NextToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +0000360 if (State.NextToken->Type == TT_ImplicitStringLiteral) {
361 // Calculating the column is important for aligning trailing comments.
362 // FIXME: This does not seem to happen in conjunction with escaped
363 // newlines. If it does, fix!
364 State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
365 State.NextToken->FormatTok.TokenLength;
366 State.NextToken = State.NextToken->Children.empty() ? NULL :
367 &State.NextToken->Children[0];
368 } else if (Line.Last->TotalLength <= getColumnLimit() - FirstIndent) {
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000369 addTokenToState(false, false, State);
370 } else {
371 unsigned NoBreak = calcPenalty(State, false, UINT_MAX);
372 unsigned Break = calcPenalty(State, true, NoBreak);
Manuel Klimek24998102013-01-16 14:55:28 +0000373 DEBUG({
374 if (Break < NoBreak)
375 llvm::errs() << "\n";
376 else
377 llvm::errs() << " ";
378 llvm::errs() << "<";
379 DebugPenalty(Break, Break < NoBreak);
380 llvm::errs() << "/";
381 DebugPenalty(NoBreak, !(Break < NoBreak));
382 llvm::errs() << "> ";
383 DebugTokenState(*State.NextToken);
384 });
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000385 addTokenToState(Break < NoBreak, false, State);
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000386 if (State.NextToken != NULL &&
387 State.NextToken->Parent->Type == TT_CtorInitializerColon) {
388 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine &&
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000389 Line.Last->TotalLength > getColumnLimit() - State.Column - 1)
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000390 State.Stack.back().BreakAfterComma = true;
391 }
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000392 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000393 }
Manuel Klimek24998102013-01-16 14:55:28 +0000394 DEBUG(llvm::errs() << "\n");
Manuel Klimek1abf7892013-01-04 23:34:14 +0000395 return State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000396 }
397
398private:
Manuel Klimek24998102013-01-16 14:55:28 +0000399 void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
400 const Token &Tok = AnnotatedTok.FormatTok.Tok;
401 llvm::errs()
402 << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
403 Tok.getLength());
404 llvm::errs();
405 }
406
407 void DebugPenalty(unsigned Penalty, bool Winner) {
408 llvm::errs().changeColor(Winner ? raw_ostream::GREEN : raw_ostream::RED);
409 if (Penalty == UINT_MAX)
410 llvm::errs() << "MAX";
411 else
412 llvm::errs() << Penalty;
413 llvm::errs().resetColor();
414 }
415
Daniel Jasper337816e2013-01-11 10:22:12 +0000416 struct ParenState {
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000417 ParenState(unsigned Indent, unsigned LastSpace)
418 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
Daniel Jasper9278eb92013-01-16 14:59:02 +0000419 BreakBeforeClosingBrace(false), BreakAfterComma(false),
420 HasMultiParameterLine(false) {}
Daniel Jasper6d822722012-12-24 16:43:00 +0000421
Daniel Jasperf7935112012-12-03 18:12:45 +0000422 /// \brief The position to which a specific parenthesis level needs to be
423 /// indented.
Daniel Jasper337816e2013-01-11 10:22:12 +0000424 unsigned Indent;
Daniel Jasperf7935112012-12-03 18:12:45 +0000425
Daniel Jaspere9de2602012-12-06 09:56:08 +0000426 /// \brief The position of the last space on each level.
427 ///
428 /// Used e.g. to break like:
429 /// functionCall(Parameter, otherCall(
430 /// OtherParameter));
Daniel Jasper337816e2013-01-11 10:22:12 +0000431 unsigned LastSpace;
Daniel Jasperf7935112012-12-03 18:12:45 +0000432
Daniel Jaspere9de2602012-12-06 09:56:08 +0000433 /// \brief The position the first "<<" operator encountered on each level.
434 ///
435 /// Used to align "<<" operators. 0 if no such operator has been encountered
436 /// on a level.
Daniel Jasper337816e2013-01-11 10:22:12 +0000437 unsigned FirstLessLess;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000438
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000439 /// \brief Whether a newline needs to be inserted before the block's closing
440 /// brace.
441 ///
442 /// We only want to insert a newline before the closing brace if there also
443 /// was a newline after the beginning left brace.
Daniel Jasper337816e2013-01-11 10:22:12 +0000444 bool BreakBeforeClosingBrace;
445
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000446 bool BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000447 bool HasMultiParameterLine;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000448
Daniel Jasper337816e2013-01-11 10:22:12 +0000449 bool operator<(const ParenState &Other) const {
450 if (Indent != Other.Indent)
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000451 return Indent < Other.Indent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000452 if (LastSpace != Other.LastSpace)
453 return LastSpace < Other.LastSpace;
454 if (FirstLessLess != Other.FirstLessLess)
455 return FirstLessLess < Other.FirstLessLess;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000456 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
457 return BreakBeforeClosingBrace;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000458 if (BreakAfterComma != Other.BreakAfterComma)
459 return BreakAfterComma;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000460 if (HasMultiParameterLine != Other.HasMultiParameterLine)
461 return HasMultiParameterLine;
Daniel Jasper7b7877a2013-01-12 07:36:22 +0000462 return false;
Daniel Jasper337816e2013-01-11 10:22:12 +0000463 }
464 };
465
466 /// \brief The current state when indenting a unwrapped line.
467 ///
468 /// As the indenting tries different combinations this is copied by value.
469 struct LineState {
470 /// \brief The number of used columns in the current line.
471 unsigned Column;
472
473 /// \brief The token that needs to be next formatted.
474 const AnnotatedToken *NextToken;
475
476 /// \brief The parenthesis level of the first token on the current line.
477 unsigned StartOfLineLevel;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000478
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000479 /// \brief The column of the first variable in a for-loop declaration.
480 ///
481 /// Used to align the second variable if necessary.
482 unsigned ForLoopVariablePos;
483
484 /// \brief \c true if this line contains a continued for-loop section.
485 bool LineContainsContinuedForLoopSection;
486
Daniel Jasper337816e2013-01-11 10:22:12 +0000487 /// \brief A stack keeping track of properties applying to parenthesis
488 /// levels.
489 std::vector<ParenState> Stack;
490
491 /// \brief Comparison operator to be able to used \c LineState in \c map.
492 bool operator<(const LineState &Other) const {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000493 if (Other.NextToken != NextToken)
494 return Other.NextToken > NextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000495 if (Other.Column != Column)
496 return Other.Column > Column;
Daniel Jasper6d822722012-12-24 16:43:00 +0000497 if (Other.StartOfLineLevel != StartOfLineLevel)
498 return Other.StartOfLineLevel > StartOfLineLevel;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000499 if (Other.ForLoopVariablePos != ForLoopVariablePos)
500 return Other.ForLoopVariablePos < ForLoopVariablePos;
501 if (Other.LineContainsContinuedForLoopSection !=
502 LineContainsContinuedForLoopSection)
503 return LineContainsContinuedForLoopSection;
Daniel Jasper337816e2013-01-11 10:22:12 +0000504 return Other.Stack < Stack;
Daniel Jasperf7935112012-12-03 18:12:45 +0000505 }
506 };
507
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000508 /// \brief Appends the next token to \p State and updates information
509 /// necessary for indentation.
510 ///
511 /// Puts the token on the current line if \p Newline is \c true and adds a
512 /// line break and necessary indentation otherwise.
513 ///
514 /// If \p DryRun is \c false, also creates and stores the required
515 /// \c Replacement.
Daniel Jasper337816e2013-01-11 10:22:12 +0000516 void addTokenToState(bool Newline, bool DryRun, LineState &State) {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000517 const AnnotatedToken &Current = *State.NextToken;
518 const AnnotatedToken &Previous = *State.NextToken->Parent;
Daniel Jasper337816e2013-01-11 10:22:12 +0000519 assert(State.Stack.size());
520 unsigned ParenLevel = State.Stack.size() - 1;
Daniel Jasperf7935112012-12-03 18:12:45 +0000521
522 if (Newline) {
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000523 unsigned WhitespaceStartColumn = State.Column;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000524 if (Current.is(tok::r_brace)) {
525 State.Column = Line.Level * 2;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000526 } else if (Current.is(tok::string_literal) &&
527 Previous.is(tok::string_literal)) {
528 State.Column = State.Column - Previous.FormatTok.TokenLength;
529 } else if (Current.is(tok::lessless) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000530 State.Stack[ParenLevel].FirstLessLess != 0) {
531 State.Column = State.Stack[ParenLevel].FirstLessLess;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000532 } else if (ParenLevel != 0 &&
Daniel Jasper399d24b2013-01-09 07:06:56 +0000533 (Previous.is(tok::equal) || Current.is(tok::arrow) ||
534 Current.is(tok::period) || Previous.is(tok::question) ||
535 Previous.Type == TT_ConditionalExpr)) {
536 // Indent and extra 4 spaces after if we know the current expression is
537 // continued. Don't do that on the top level, as we already indent 4
538 // there.
Daniel Jasper337816e2013-01-11 10:22:12 +0000539 State.Column = State.Stack[ParenLevel].Indent + 4;
Daniel Jasper399d24b2013-01-09 07:06:56 +0000540 } else if (RootToken.is(tok::kw_for) && Previous.is(tok::comma)) {
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000541 State.Column = State.ForLoopVariablePos;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000542 } else if (State.NextToken->Parent->ClosesTemplateDeclaration) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000543 State.Column = State.Stack[ParenLevel].Indent - 4;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000544 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000545 State.Column = State.Stack[ParenLevel].Indent;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000546 }
547
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000548 // A line starting with a closing brace is assumed to be correct for the
549 // same level as before the opening brace.
550 State.StartOfLineLevel = ParenLevel + (Current.is(tok::r_brace) ? 0 : 1);
Daniel Jasper6d822722012-12-24 16:43:00 +0000551
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000552 if (RootToken.is(tok::kw_for))
Daniel Jasper399d24b2013-01-09 07:06:56 +0000553 State.LineContainsContinuedForLoopSection = Previous.isNot(tok::semi);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000554
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000555 if (!DryRun) {
556 if (!Line.InPPDirective)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000557 Whitespaces.replaceWhitespace(Current, 1, State.Column,
558 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000559 else
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000560 Whitespaces.replacePPWhitespace(Current, 1, State.Column,
561 WhitespaceStartColumn, Style);
Manuel Klimekb69e3c62013-01-02 18:33:23 +0000562 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000563
Daniel Jasper337816e2013-01-11 10:22:12 +0000564 State.Stack[ParenLevel].LastSpace = State.Column;
Nico Webercb465dc2013-01-12 07:05:25 +0000565 if (Current.is(tok::colon) && State.NextToken->Type != TT_ConditionalExpr)
Daniel Jasper337816e2013-01-11 10:22:12 +0000566 State.Stack[ParenLevel].Indent += 2;
Daniel Jasperf7935112012-12-03 18:12:45 +0000567 } else {
Daniel Jasper399d24b2013-01-09 07:06:56 +0000568 if (Current.is(tok::equal) && RootToken.is(tok::kw_for))
569 State.ForLoopVariablePos = State.Column -
570 Previous.FormatTok.TokenLength;
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000571
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000572 unsigned Spaces = State.NextToken->SpaceRequiredBefore ? 1 : 0;
573 if (State.NextToken->Type == TT_LineComment)
Daniel Jasper5ad1e192013-01-07 11:09:06 +0000574 Spaces = Style.SpacesBeforeTrailingComments;
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000575
Daniel Jasperf7935112012-12-03 18:12:45 +0000576 if (!DryRun)
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000577 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000578
Daniel Jasperbcab4302013-01-09 10:40:23 +0000579 // FIXME: Do we need to do this for assignments nested in other
580 // expressions?
581 if (RootToken.isNot(tok::kw_for) && ParenLevel == 0 &&
Daniel Jasper206df732013-01-07 13:08:40 +0000582 (getPrecedence(Previous) == prec::Assignment ||
Daniel Jasper399d24b2013-01-09 07:06:56 +0000583 Previous.is(tok::kw_return)))
Daniel Jasper337816e2013-01-11 10:22:12 +0000584 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasperfd8c4b12013-01-11 14:23:32 +0000585 if (Previous.is(tok::l_paren) || Previous.is(tok::l_brace) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000586 State.NextToken->Parent->Type == TT_TemplateOpener)
Daniel Jasper337816e2013-01-11 10:22:12 +0000587 State.Stack[ParenLevel].Indent = State.Column + Spaces;
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000588 if (Current.getPreviousNoneComment()->is(tok::comma) &&
589 Current.isNot(tok::comment))
Daniel Jasper9278eb92013-01-16 14:59:02 +0000590 State.Stack[ParenLevel].HasMultiParameterLine = true;
591
Daniel Jasper2af6bbe2012-12-18 21:05:13 +0000592
Daniel Jasper206df732013-01-07 13:08:40 +0000593 // Top-level spaces that are not part of assignments are exempt as that
594 // mostly leads to better results.
Daniel Jaspere9de2602012-12-06 09:56:08 +0000595 State.Column += Spaces;
Daniel Jasper206df732013-01-07 13:08:40 +0000596 if (Spaces > 0 &&
597 (ParenLevel != 0 || getPrecedence(Previous) == prec::Assignment))
Daniel Jasper337816e2013-01-11 10:22:12 +0000598 State.Stack[ParenLevel].LastSpace = State.Column;
Daniel Jasperf7935112012-12-03 18:12:45 +0000599 }
Daniel Jasper9278eb92013-01-16 14:59:02 +0000600
601 // If we break after an {, we should also break before the corresponding }.
602 if (Newline && Previous.is(tok::l_brace))
Daniel Jasper337816e2013-01-11 10:22:12 +0000603 State.Stack.back().BreakBeforeClosingBrace = true;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000604
605 // If we are breaking after '(', '{', '<' or ',', we need to break after
606 // future commas as well to avoid bin packing.
607 if (!Style.BinPackParameters && Newline &&
608 (Previous.is(tok::comma) || Previous.is(tok::l_paren) ||
609 Previous.is(tok::l_brace) || Previous.Type == TT_TemplateOpener))
610 State.Stack.back().BreakAfterComma = true;
611
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000612 moveStateToNextToken(State);
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000613 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000614
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000615 /// \brief Mark the next token as consumed in \p State and modify its stacks
616 /// accordingly.
Daniel Jasper337816e2013-01-11 10:22:12 +0000617 void moveStateToNextToken(LineState &State) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000618 const AnnotatedToken &Current = *State.NextToken;
Daniel Jasper337816e2013-01-11 10:22:12 +0000619 assert(State.Stack.size());
Daniel Jaspere9de2602012-12-06 09:56:08 +0000620
Daniel Jasper337816e2013-01-11 10:22:12 +0000621 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
622 State.Stack.back().FirstLessLess = State.Column;
Daniel Jaspere9de2602012-12-06 09:56:08 +0000623
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000624 // If we encounter an opening (, [, { or <, we add a level to our stacks to
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000625 // prepare for the following tokens.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000626 if (Current.is(tok::l_paren) || Current.is(tok::l_square) ||
627 Current.is(tok::l_brace) ||
628 State.NextToken->Type == TT_TemplateOpener) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000629 unsigned NewIndent;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000630 if (Current.is(tok::l_brace)) {
631 // FIXME: This does not work with nested static initializers.
632 // Implement a better handling for static initializers and similar
633 // constructs.
Daniel Jasper337816e2013-01-11 10:22:12 +0000634 NewIndent = Line.Level * 2 + 2;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000635 } else {
Daniel Jasper337816e2013-01-11 10:22:12 +0000636 NewIndent = 4 + State.Stack.back().LastSpace;
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000637 }
Daniel Jasper337816e2013-01-11 10:22:12 +0000638 State.Stack.push_back(
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000639 ParenState(NewIndent, State.Stack.back().LastSpace));
Daniel Jasper9278eb92013-01-16 14:59:02 +0000640
641 // If the entire set of parameters will not fit on the current line, we
642 // will need to break after commas on this level to avoid bin-packing.
643 if (!Style.BinPackParameters && Current.MatchingParen != NULL &&
644 !Current.Children.empty()) {
645 if (getColumnLimit() < State.Column + Current.FormatTok.TokenLength +
646 Current.MatchingParen->TotalLength -
647 Current.Children[0].TotalLength) {
648 State.Stack.back().BreakAfterComma = true;
649 }
650 }
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000651 }
652
Daniel Jasper2eda23e2012-12-24 13:43:52 +0000653 // If we encounter a closing ), ], } or >, we can remove a level from our
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000654 // stacks.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000655 if (Current.is(tok::r_paren) || Current.is(tok::r_square) ||
656 (Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
657 State.NextToken->Type == TT_TemplateCloser) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000658 State.Stack.pop_back();
Daniel Jasperf7935112012-12-03 18:12:45 +0000659 }
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000660
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000661 if (State.NextToken->Children.empty())
662 State.NextToken = NULL;
663 else
664 State.NextToken = &State.NextToken->Children[0];
Manuel Klimek73a2fdf2013-01-10 14:36:46 +0000665
666 State.Column += Current.FormatTok.TokenLength;
Daniel Jasperf7935112012-12-03 18:12:45 +0000667 }
668
Nico Weber49cbc2c2013-01-07 15:15:29 +0000669 /// \brief Calculate the penalty for splitting after the token at \p Index.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000670 unsigned splitPenalty(const AnnotatedToken &Tok) {
671 const AnnotatedToken &Left = Tok;
672 const AnnotatedToken &Right = Tok.Children[0];
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000673
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000674 if (Left.is(tok::l_brace) && Right.isNot(tok::l_brace))
675 return 50;
676 if (Left.is(tok::equal) && Right.is(tok::l_brace))
677 return 150;
678
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000679 // In for-loops, prefer breaking at ',' and ';'.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000680 if (RootToken.is(tok::kw_for) &&
681 (Left.isNot(tok::comma) && Left.isNot(tok::semi)))
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000682 return 20;
683
Daniel Jasper04468962013-01-18 10:56:38 +0000684 if (Left.is(tok::semi) || Left.is(tok::comma))
Daniel Jasperf7935112012-12-03 18:12:45 +0000685 return 0;
Nico Weberc9d73612013-01-12 22:48:47 +0000686
687 // In Objective-C method expressions, prefer breaking before "param:" over
688 // breaking after it.
689 if (isObjCSelectorName(Right))
690 return 0;
691 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
692 return 20;
693
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000694 if (Left.is(tok::l_paren))
Daniel Jasper3d0c75c2013-01-02 14:40:02 +0000695 return 20;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000696
Daniel Jasper399d24b2013-01-09 07:06:56 +0000697 if (Left.is(tok::question) || Left.Type == TT_ConditionalExpr)
698 return prec::Assignment;
Daniel Jasper206df732013-01-07 13:08:40 +0000699 prec::Level Level = getPrecedence(Left);
700
701 // Breaking after an assignment leads to a bad result as the two sides of
702 // the assignment are visually very close together.
703 if (Level == prec::Assignment)
704 return 50;
705
Daniel Jasperde5c2072012-12-24 00:13:23 +0000706 if (Level != prec::Unknown)
707 return Level;
708
Daniel Jasper04468962013-01-18 10:56:38 +0000709 if (Right.is(tok::arrow) || Right.is(tok::period)) {
710 if (Left.is(tok::r_paren))
711 return 15; // Should be smaller than breaking at a nested comma.
Daniel Jasperc7345cc2013-01-07 07:13:20 +0000712 return 150;
Daniel Jasper04468962013-01-18 10:56:38 +0000713 }
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000714
Daniel Jasperf7935112012-12-03 18:12:45 +0000715 return 3;
716 }
717
Daniel Jasper2df93312013-01-09 10:16:05 +0000718 unsigned getColumnLimit() {
719 return Style.ColumnLimit - (Line.InPPDirective ? 1 : 0);
720 }
721
Daniel Jasperf7935112012-12-03 18:12:45 +0000722 /// \brief Calculate the number of lines needed to format the remaining part
723 /// of the unwrapped line.
724 ///
725 /// Assumes the formatting so far has led to
Daniel Jasper337816e2013-01-11 10:22:12 +0000726 /// the \c LineSta \p State. If \p NewLine is set, a new line will be
Daniel Jasperf7935112012-12-03 18:12:45 +0000727 /// added after the previous token.
728 ///
729 /// \param StopAt is used for optimization. If we can determine that we'll
730 /// definitely need at least \p StopAt additional lines, we already know of a
731 /// better solution.
Daniel Jasper337816e2013-01-11 10:22:12 +0000732 unsigned calcPenalty(LineState State, bool NewLine, unsigned StopAt) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000733 // We are at the end of the unwrapped line, so we don't need any more lines.
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000734 if (State.NextToken == NULL)
Daniel Jasperf7935112012-12-03 18:12:45 +0000735 return 0;
736
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000737 if (!NewLine && State.NextToken->MustBreakBefore)
Daniel Jasperf7935112012-12-03 18:12:45 +0000738 return UINT_MAX;
Manuel Klimeka54d1a92013-01-14 16:41:43 +0000739 if (NewLine && !State.NextToken->CanBreakBefore &&
740 !(State.NextToken->is(tok::r_brace) &&
741 State.Stack.back().BreakBeforeClosingBrace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000742 return UINT_MAX;
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000743 if (!NewLine && State.NextToken->is(tok::r_brace) &&
Daniel Jasper337816e2013-01-11 10:22:12 +0000744 State.Stack.back().BreakBeforeClosingBrace)
Manuel Klimek0ddd57a2013-01-10 15:58:26 +0000745 return UINT_MAX;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000746 if (!NewLine && State.NextToken->Parent->is(tok::semi) &&
Daniel Jasperfbde69e2012-12-21 14:37:20 +0000747 State.LineContainsContinuedForLoopSection)
748 return UINT_MAX;
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000749 if (!NewLine && State.NextToken->Parent->is(tok::comma) &&
Daniel Jasper11cb81c2013-01-17 12:53:34 +0000750 State.NextToken->isNot(tok::comment) &&
Daniel Jasper2408a8c2013-01-11 11:37:55 +0000751 State.Stack.back().BreakAfterComma)
752 return UINT_MAX;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000753 // Trying to insert a parameter on a new line if there are already more than
754 // one parameter on the current line is bin packing.
755 if (NewLine && State.NextToken->Parent->is(tok::comma) &&
756 State.Stack.back().HasMultiParameterLine && !Style.BinPackParameters)
757 return UINT_MAX;
Daniel Jasper04468962013-01-18 10:56:38 +0000758 if (!NewLine && (State.NextToken->Type == TT_CtorInitializerColon ||
759 (State.NextToken->Parent->ClosesTemplateDeclaration &&
760 State.Stack.size() == 1)))
Daniel Jaspera67a8f02013-01-16 10:41:46 +0000761 return UINT_MAX;
Daniel Jasperf7935112012-12-03 18:12:45 +0000762
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000763 unsigned CurrentPenalty = 0;
764 if (NewLine) {
Daniel Jasper337816e2013-01-11 10:22:12 +0000765 CurrentPenalty += Parameters.PenaltyIndentLevel * State.Stack.size() +
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000766 splitPenalty(*State.NextToken->Parent);
Daniel Jasper6d822722012-12-24 16:43:00 +0000767 } else {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000768 if (State.Stack.size() < State.StartOfLineLevel &&
769 State.NextToken->is(tok::identifier))
Daniel Jasper6d822722012-12-24 16:43:00 +0000770 CurrentPenalty += Parameters.PenaltyLevelDecrease *
Daniel Jasper337816e2013-01-11 10:22:12 +0000771 (State.StartOfLineLevel - State.Stack.size());
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000772 }
773
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000774 addTokenToState(NewLine, true, State);
Daniel Jasperf7935112012-12-03 18:12:45 +0000775
Daniel Jasper2df93312013-01-09 10:16:05 +0000776 // Exceeding column limit is bad, assign penalty.
777 if (State.Column > getColumnLimit()) {
778 unsigned ExcessCharacters = State.Column - getColumnLimit();
779 CurrentPenalty += Parameters.PenaltyExcessCharacter * ExcessCharacters;
780 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000781
Daniel Jasperf7935112012-12-03 18:12:45 +0000782 if (StopAt <= CurrentPenalty)
783 return UINT_MAX;
784 StopAt -= CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000785 StateMap::iterator I = Memory.find(State);
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000786 if (I != Memory.end()) {
787 // If this state has already been examined, we can safely return the
788 // previous result if we
789 // - have not hit the optimatization (and thus returned UINT_MAX) OR
790 // - are now computing for a smaller or equal StopAt.
791 unsigned SavedResult = I->second.first;
792 unsigned SavedStopAt = I->second.second;
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000793 if (SavedResult != UINT_MAX)
794 return SavedResult + CurrentPenalty;
795 else if (StopAt <= SavedStopAt)
796 return UINT_MAX;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000797 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000798
799 unsigned NoBreak = calcPenalty(State, false, StopAt);
800 unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak));
801 unsigned Result = std::min(NoBreak, WithBreak);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000802
803 // We have to store 'Result' without adding 'CurrentPenalty' as the latter
804 // can depend on 'NewLine'.
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000805 Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt);
Daniel Jasper5485d0c2012-12-17 14:34:14 +0000806
807 return Result == UINT_MAX ? UINT_MAX : Result + CurrentPenalty;
Daniel Jasperf7935112012-12-03 18:12:45 +0000808 }
809
Daniel Jasperf7935112012-12-03 18:12:45 +0000810 FormatStyle Style;
811 SourceManager &SourceMgr;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000812 const AnnotatedLine &Line;
Manuel Klimek0b689fd2013-01-10 18:45:26 +0000813 const unsigned FirstIndent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000814 const AnnotatedToken &RootToken;
Daniel Jasperaa701fa2013-01-18 08:44:07 +0000815 WhitespaceManager &Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +0000816
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000817 // A map from an indent state to a pair (Result, Used-StopAt).
Daniel Jasper337816e2013-01-11 10:22:12 +0000818 typedef std::map<LineState, std::pair<unsigned, unsigned> > StateMap;
Daniel Jasperaa1c9202012-12-05 14:57:28 +0000819 StateMap Memory;
820
Daniel Jasperf7935112012-12-03 18:12:45 +0000821 OptimizationParameters Parameters;
822};
823
824/// \brief Determines extra information about the tokens comprising an
825/// \c UnwrappedLine.
826class TokenAnnotator {
827public:
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +0000828 TokenAnnotator(const FormatStyle &Style, SourceManager &SourceMgr, Lexer &Lex,
829 AnnotatedLine &Line)
830 : Style(Style), SourceMgr(SourceMgr), Lex(Lex), Line(Line) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000831
832 /// \brief A parser that gathers additional information about tokens.
833 ///
834 /// The \c TokenAnnotator tries to matches parenthesis and square brakets and
835 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
836 /// into template parameter lists.
837 class AnnotatingParser {
838 public:
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000839 AnnotatingParser(AnnotatedToken &RootToken)
Nico Webera7252d82013-01-12 06:18:40 +0000840 : CurrentToken(&RootToken), KeywordVirtualFound(false),
841 ColonIsObjCMethodExpr(false) {}
Daniel Jasperf7935112012-12-03 18:12:45 +0000842
Nico Weber250fe712013-01-18 02:43:57 +0000843 /// \brief A helper class to manage AnnotatingParser::ColonIsObjCMethodExpr.
844 struct ObjCSelectorRAII {
845 AnnotatingParser &P;
846 bool ColonWasObjCMethodExpr;
847
848 ObjCSelectorRAII(AnnotatingParser &P)
849 : P(P), ColonWasObjCMethodExpr(P.ColonIsObjCMethodExpr) {}
850
851 ~ObjCSelectorRAII() { P.ColonIsObjCMethodExpr = ColonWasObjCMethodExpr; }
852
853 void markStart(AnnotatedToken &Left) {
854 P.ColonIsObjCMethodExpr = true;
855 Left.Type = TT_ObjCMethodExpr;
856 }
857
858 void markEnd(AnnotatedToken &Right) { Right.Type = TT_ObjCMethodExpr; }
859 };
860
861
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000862 bool parseAngle() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000863 if (CurrentToken == NULL)
864 return false;
865 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000866 while (CurrentToken != NULL) {
867 if (CurrentToken->is(tok::greater)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000868 Left->MatchingParen = CurrentToken;
869 CurrentToken->MatchingParen = Left;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000870 CurrentToken->Type = TT_TemplateCloser;
Daniel Jasperf7935112012-12-03 18:12:45 +0000871 next();
872 return true;
873 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000874 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square) ||
875 CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000876 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000877 if (CurrentToken->is(tok::pipepipe) || CurrentToken->is(tok::ampamp) ||
878 CurrentToken->is(tok::question) || CurrentToken->is(tok::colon))
Daniel Jasperf7935112012-12-03 18:12:45 +0000879 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000880 if (!consumeToken())
881 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000882 }
883 return false;
884 }
885
Nico Weber80a82762013-01-17 17:17:19 +0000886 bool parseParens(bool LookForDecls = false) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000887 if (CurrentToken == NULL)
888 return false;
Nico Weber250fe712013-01-18 02:43:57 +0000889 bool StartsObjCMethodExpr = false;
Daniel Jasper9278eb92013-01-16 14:59:02 +0000890 AnnotatedToken *Left = CurrentToken->Parent;
Nico Weber250fe712013-01-18 02:43:57 +0000891 if (CurrentToken->is(tok::caret)) {
892 // ^( starts a block.
Daniel Jasper9278eb92013-01-16 14:59:02 +0000893 Left->Type = TT_ObjCBlockLParen;
Nico Weber250fe712013-01-18 02:43:57 +0000894 } else if (AnnotatedToken *MaybeSel = Left->Parent) {
895 // @selector( starts a selector.
896 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Parent &&
897 MaybeSel->Parent->is(tok::at)) {
898 StartsObjCMethodExpr = true;
899 }
900 }
901
902 ObjCSelectorRAII objCSelector(*this);
903 if (StartsObjCMethodExpr)
904 objCSelector.markStart(*Left);
905
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000906 while (CurrentToken != NULL) {
Nico Weber80a82762013-01-17 17:17:19 +0000907 // LookForDecls is set when "if (" has been seen. Check for
908 // 'identifier' '*' 'identifier' followed by not '=' -- this
909 // '*' has to be a binary operator but determineStarAmpUsage() will
910 // categorize it as an unary operator, so set the right type here.
911 if (LookForDecls && !CurrentToken->Children.empty()) {
912 AnnotatedToken &Prev = *CurrentToken->Parent;
913 AnnotatedToken &Next = CurrentToken->Children[0];
914 if (Prev.Parent->is(tok::identifier) &&
915 (Prev.is(tok::star) || Prev.is(tok::amp)) &&
916 CurrentToken->is(tok::identifier) && Next.isNot(tok::equal)) {
917 Prev.Type = TT_BinaryOperator;
918 LookForDecls = false;
919 }
920 }
921
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000922 if (CurrentToken->is(tok::r_paren)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000923 Left->MatchingParen = CurrentToken;
924 CurrentToken->MatchingParen = Left;
Nico Weber250fe712013-01-18 02:43:57 +0000925
926 if (StartsObjCMethodExpr)
927 objCSelector.markEnd(*CurrentToken);
928
Daniel Jasperf7935112012-12-03 18:12:45 +0000929 next();
930 return true;
931 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000932 if (CurrentToken->is(tok::r_square) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000933 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000934 if (!consumeToken())
935 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000936 }
937 return false;
938 }
939
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000940 bool parseSquare() {
Nico Webera7252d82013-01-12 06:18:40 +0000941 if (!CurrentToken)
942 return false;
943
944 // A '[' could be an index subscript (after an indentifier or after
945 // ')' or ']'), or it could be the start of an Objective-C method
946 // expression.
Nico Webered272de2013-01-21 19:29:31 +0000947 AnnotatedToken *Left = CurrentToken->Parent;
Nico Webera7252d82013-01-12 06:18:40 +0000948 bool StartsObjCMethodExpr =
Nico Webered272de2013-01-21 19:29:31 +0000949 !Left->Parent || Left->Parent->is(tok::colon) ||
950 Left->Parent->is(tok::l_square) || Left->Parent->is(tok::l_paren) ||
951 Left->Parent->is(tok::kw_return) || Left->Parent->is(tok::kw_throw) ||
952 getBinOpPrecedence(Left->Parent->FormatTok.Tok.getKind(),
Nico Webera7252d82013-01-12 06:18:40 +0000953 true, true) > prec::Unknown;
954
Nico Weber250fe712013-01-18 02:43:57 +0000955 ObjCSelectorRAII objCSelector(*this);
956 if (StartsObjCMethodExpr)
Nico Webered272de2013-01-21 19:29:31 +0000957 objCSelector.markStart(*Left);
Nico Webera7252d82013-01-12 06:18:40 +0000958
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000959 while (CurrentToken != NULL) {
960 if (CurrentToken->is(tok::r_square)) {
Nico Weber250fe712013-01-18 02:43:57 +0000961 if (StartsObjCMethodExpr)
962 objCSelector.markEnd(*CurrentToken);
Nico Weber767c8d32013-01-21 19:35:06 +0000963 Left->MatchingParen = CurrentToken;
964 CurrentToken->MatchingParen = Left;
Daniel Jasperf7935112012-12-03 18:12:45 +0000965 next();
966 return true;
967 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000968 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_brace))
Daniel Jasperf7935112012-12-03 18:12:45 +0000969 return false;
Daniel Jasperc0880a92013-01-04 18:52:56 +0000970 if (!consumeToken())
971 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000972 }
973 return false;
974 }
975
Daniel Jasper83a54d22013-01-10 09:26:47 +0000976 bool parseBrace() {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000977 // Lines are fine to end with '{'.
978 if (CurrentToken == NULL)
979 return true;
980 AnnotatedToken *Left = CurrentToken->Parent;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000981 while (CurrentToken != NULL) {
982 if (CurrentToken->is(tok::r_brace)) {
Daniel Jasper9278eb92013-01-16 14:59:02 +0000983 Left->MatchingParen = CurrentToken;
984 CurrentToken->MatchingParen = Left;
Daniel Jasper83a54d22013-01-10 09:26:47 +0000985 next();
986 return true;
987 }
988 if (CurrentToken->is(tok::r_paren) || CurrentToken->is(tok::r_square))
989 return false;
990 if (!consumeToken())
991 return false;
992 }
Daniel Jasper83a54d22013-01-10 09:26:47 +0000993 return true;
994 }
995
Daniel Jasper6021c4a2012-12-04 14:54:30 +0000996 bool parseConditional() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +0000997 while (CurrentToken != NULL) {
998 if (CurrentToken->is(tok::colon)) {
999 CurrentToken->Type = TT_ConditionalExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001000 next();
1001 return true;
1002 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001003 if (!consumeToken())
1004 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001005 }
1006 return false;
1007 }
1008
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001009 bool parseTemplateDeclaration() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001010 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1011 CurrentToken->Type = TT_TemplateOpener;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001012 next();
1013 if (!parseAngle())
1014 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001015 CurrentToken->Parent->ClosesTemplateDeclaration = true;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001016 return true;
1017 }
1018 return false;
1019 }
1020
Daniel Jasperc0880a92013-01-04 18:52:56 +00001021 bool consumeToken() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001022 AnnotatedToken *Tok = CurrentToken;
Daniel Jasperf7935112012-12-03 18:12:45 +00001023 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001024 switch (Tok->FormatTok.Tok.getKind()) {
Nico Weber9efe2912013-01-10 23:11:41 +00001025 case tok::plus:
1026 case tok::minus:
1027 // At the start of the line, +/- specific ObjectiveC method
1028 // declarations.
1029 if (Tok->Parent == NULL)
1030 Tok->Type = TT_ObjCMethodSpecifier;
1031 break;
Nico Webera7252d82013-01-12 06:18:40 +00001032 case tok::colon:
1033 // Colons from ?: are handled in parseConditional().
Daniel Jasper8c5fba92013-01-16 16:23:19 +00001034 if (Tok->Parent->is(tok::r_paren))
1035 Tok->Type = TT_CtorInitializerColon;
Nico Webera7252d82013-01-12 06:18:40 +00001036 if (ColonIsObjCMethodExpr)
1037 Tok->Type = TT_ObjCMethodExpr;
1038 break;
Nico Weber80a82762013-01-17 17:17:19 +00001039 case tok::kw_if:
1040 case tok::kw_while:
1041 if (CurrentToken->is(tok::l_paren)) {
1042 next();
1043 if (!parseParens(/*LookForDecls=*/true))
1044 return false;
1045 }
1046 break;
Nico Webera5510af2013-01-18 05:50:57 +00001047 case tok::l_paren:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001048 if (!parseParens())
1049 return false;
Nico Webera5510af2013-01-18 05:50:57 +00001050 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001051 case tok::l_square:
Daniel Jasperc0880a92013-01-04 18:52:56 +00001052 if (!parseSquare())
1053 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001054 break;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001055 case tok::l_brace:
1056 if (!parseBrace())
1057 return false;
1058 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001059 case tok::less:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001060 if (parseAngle())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001061 Tok->Type = TT_TemplateOpener;
Daniel Jasperf7935112012-12-03 18:12:45 +00001062 else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001063 Tok->Type = TT_BinaryOperator;
1064 CurrentToken = Tok;
1065 next();
Daniel Jasperf7935112012-12-03 18:12:45 +00001066 }
1067 break;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001068 case tok::r_paren:
1069 case tok::r_square:
1070 return false;
Daniel Jasper83a54d22013-01-10 09:26:47 +00001071 case tok::r_brace:
1072 // Lines can start with '}'.
1073 if (Tok->Parent != NULL)
1074 return false;
1075 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001076 case tok::greater:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001077 Tok->Type = TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001078 break;
1079 case tok::kw_operator:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001080 if (CurrentToken->is(tok::l_paren)) {
1081 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001082 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001083 if (CurrentToken != NULL && CurrentToken->is(tok::r_paren)) {
1084 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001085 next();
1086 }
1087 } else {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001088 while (CurrentToken != NULL && CurrentToken->isNot(tok::l_paren)) {
1089 CurrentToken->Type = TT_OverloadedOperator;
Daniel Jasper537a2962012-12-24 10:56:04 +00001090 next();
1091 }
1092 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001093 break;
1094 case tok::question:
Daniel Jasper6021c4a2012-12-04 14:54:30 +00001095 parseConditional();
Daniel Jasperf7935112012-12-03 18:12:45 +00001096 break;
Daniel Jasperac5c1c22013-01-02 15:08:56 +00001097 case tok::kw_template:
1098 parseTemplateDeclaration();
1099 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001100 default:
1101 break;
1102 }
Daniel Jasperc0880a92013-01-04 18:52:56 +00001103 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001104 }
1105
Daniel Jasper050948a52012-12-21 17:58:39 +00001106 void parseIncludeDirective() {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001107 next();
1108 if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
1109 next();
1110 while (CurrentToken != NULL) {
Daniel Jasper997b08c2013-01-18 09:19:33 +00001111 if (CurrentToken->isNot(tok::comment) ||
1112 !CurrentToken->Children.empty())
1113 CurrentToken->Type = TT_ImplicitStringLiteral;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001114 next();
1115 }
1116 } else {
1117 while (CurrentToken != NULL) {
1118 next();
1119 }
1120 }
1121 }
1122
1123 void parseWarningOrError() {
1124 next();
1125 // We still want to format the whitespace left of the first token of the
1126 // warning or error.
1127 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001128 while (CurrentToken != NULL) {
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001129 CurrentToken->Type = TT_ImplicitStringLiteral;
Daniel Jasper050948a52012-12-21 17:58:39 +00001130 next();
1131 }
1132 }
1133
1134 void parsePreprocessorDirective() {
1135 next();
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001136 if (CurrentToken == NULL)
Daniel Jasper050948a52012-12-21 17:58:39 +00001137 return;
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001138 // Hashes in the middle of a line can lead to any strange token
1139 // sequence.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001140 if (CurrentToken->FormatTok.Tok.getIdentifierInfo() == NULL)
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001141 return;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001142 switch (
1143 CurrentToken->FormatTok.Tok.getIdentifierInfo()->getPPKeywordID()) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001144 case tok::pp_include:
Nico Weber8f83ee42012-12-21 18:21:56 +00001145 case tok::pp_import:
Daniel Jasper050948a52012-12-21 17:58:39 +00001146 parseIncludeDirective();
1147 break;
Manuel Klimek99c7baa2013-01-15 15:50:27 +00001148 case tok::pp_error:
1149 case tok::pp_warning:
1150 parseWarningOrError();
1151 break;
Daniel Jasper050948a52012-12-21 17:58:39 +00001152 default:
1153 break;
1154 }
1155 }
1156
Daniel Jasperda16db32013-01-07 10:48:50 +00001157 LineType parseLine() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001158 if (CurrentToken->is(tok::hash)) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001159 parsePreprocessorDirective();
Daniel Jasperda16db32013-01-07 10:48:50 +00001160 return LT_PreprocessorDirective;
Daniel Jasper050948a52012-12-21 17:58:39 +00001161 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001162 while (CurrentToken != NULL) {
1163 if (CurrentToken->is(tok::kw_virtual))
Daniel Jasperda16db32013-01-07 10:48:50 +00001164 KeywordVirtualFound = true;
Daniel Jasperc0880a92013-01-04 18:52:56 +00001165 if (!consumeToken())
Daniel Jasperda16db32013-01-07 10:48:50 +00001166 return LT_Invalid;
Daniel Jasperf7935112012-12-03 18:12:45 +00001167 }
Daniel Jasperda16db32013-01-07 10:48:50 +00001168 if (KeywordVirtualFound)
1169 return LT_VirtualFunctionDecl;
1170 return LT_Other;
Daniel Jasperf7935112012-12-03 18:12:45 +00001171 }
1172
1173 void next() {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001174 if (CurrentToken != NULL && !CurrentToken->Children.empty())
1175 CurrentToken = &CurrentToken->Children[0];
1176 else
1177 CurrentToken = NULL;
Daniel Jasperf7935112012-12-03 18:12:45 +00001178 }
1179
1180 private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001181 AnnotatedToken *CurrentToken;
Daniel Jasperda16db32013-01-07 10:48:50 +00001182 bool KeywordVirtualFound;
Nico Webera7252d82013-01-12 06:18:40 +00001183 bool ColonIsObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001184 };
1185
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001186 void calculateExtraInformation(AnnotatedToken &Current) {
1187 Current.SpaceRequiredBefore = spaceRequiredBefore(Current);
1188
Manuel Klimek52b15152013-01-09 15:25:02 +00001189 if (Current.FormatTok.MustBreakBefore) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001190 Current.MustBreakBefore = true;
1191 } else {
Daniel Jasper942ee722013-01-13 16:10:20 +00001192 if (Current.Type == TT_LineComment) {
1193 Current.MustBreakBefore = Current.FormatTok.NewlinesBefore > 0;
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001194 } else if ((Current.Parent->is(tok::comment) &&
1195 Current.FormatTok.NewlinesBefore > 0) ||
Daniel Jasper942ee722013-01-13 16:10:20 +00001196 (Current.is(tok::string_literal) &&
1197 Current.Parent->is(tok::string_literal))) {
Manuel Klimek52b15152013-01-09 15:25:02 +00001198 Current.MustBreakBefore = true;
Manuel Klimek52b15152013-01-09 15:25:02 +00001199 } else {
1200 Current.MustBreakBefore = false;
1201 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001202 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001203 Current.CanBreakBefore = Current.MustBreakBefore || canBreakBefore(Current);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001204 if (Current.MustBreakBefore)
1205 Current.TotalLength = Current.Parent->TotalLength + Style.ColumnLimit;
1206 else
1207 Current.TotalLength = Current.Parent->TotalLength +
1208 Current.FormatTok.TokenLength +
1209 (Current.SpaceRequiredBefore ? 1 : 0);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001210 if (!Current.Children.empty())
1211 calculateExtraInformation(Current.Children[0]);
1212 }
1213
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001214 void annotate() {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001215 AnnotatingParser Parser(Line.First);
1216 Line.Type = Parser.parseLine();
1217 if (Line.Type == LT_Invalid)
1218 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001219
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001220 determineTokenTypes(Line.First, /*IsRHS=*/false);
Daniel Jasperda16db32013-01-07 10:48:50 +00001221
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001222 if (Line.First.Type == TT_ObjCMethodSpecifier)
1223 Line.Type = LT_ObjCMethodDecl;
1224 else if (Line.First.Type == TT_ObjCDecl)
1225 Line.Type = LT_ObjCDecl;
1226 else if (Line.First.Type == TT_ObjCProperty)
1227 Line.Type = LT_ObjCProperty;
Daniel Jasperda16db32013-01-07 10:48:50 +00001228
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001229 Line.First.SpaceRequiredBefore = true;
1230 Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
1231 Line.First.CanBreakBefore = Line.First.MustBreakBefore;
Daniel Jasperf7935112012-12-03 18:12:45 +00001232
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001233 Line.First.TotalLength = Line.First.FormatTok.TokenLength;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001234 if (!Line.First.Children.empty())
1235 calculateExtraInformation(Line.First.Children[0]);
Daniel Jasperf7935112012-12-03 18:12:45 +00001236 }
1237
1238private:
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001239 void determineTokenTypes(AnnotatedToken &Current, bool IsRHS) {
1240 if (getPrecedence(Current) == prec::Assignment ||
1241 Current.is(tok::kw_return) || Current.is(tok::kw_throw))
1242 IsRHS = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001243
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001244 if (Current.Type == TT_Unknown) {
1245 if (Current.is(tok::star) || Current.is(tok::amp)) {
1246 Current.Type = determineStarAmpUsage(Current, IsRHS);
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001247 } else if (Current.is(tok::minus) || Current.is(tok::plus) ||
1248 Current.is(tok::caret)) {
1249 Current.Type = determinePlusMinusCaretUsage(Current);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001250 } else if (Current.is(tok::minusminus) || Current.is(tok::plusplus)) {
1251 Current.Type = determineIncrementUsage(Current);
1252 } else if (Current.is(tok::exclaim)) {
1253 Current.Type = TT_UnaryOperator;
1254 } else if (isBinaryOperator(Current)) {
1255 Current.Type = TT_BinaryOperator;
1256 } else if (Current.is(tok::comment)) {
1257 std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
1258 Lex.getLangOpts()));
Manuel Klimekc74d2922013-01-07 08:54:53 +00001259 if (StringRef(Data).startswith("//"))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001260 Current.Type = TT_LineComment;
Daniel Jasperf7935112012-12-03 18:12:45 +00001261 else
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001262 Current.Type = TT_BlockComment;
Daniel Jasper7194e182013-01-10 11:14:08 +00001263 } else if (Current.is(tok::r_paren) &&
1264 (Current.Parent->Type == TT_PointerOrReference ||
Daniel Jasperef906a92013-01-13 08:01:36 +00001265 Current.Parent->Type == TT_TemplateCloser) &&
1266 (Current.Children.empty() ||
1267 (Current.Children[0].isNot(tok::equal) &&
1268 Current.Children[0].isNot(tok::semi) &&
1269 Current.Children[0].isNot(tok::l_brace)))) {
Daniel Jasper7194e182013-01-10 11:14:08 +00001270 // FIXME: We need to get smarter and understand more cases of casts.
1271 Current.Type = TT_CastRParen;
Nico Weber2bb00742013-01-10 19:19:14 +00001272 } else if (Current.is(tok::at) && Current.Children.size()) {
1273 switch (Current.Children[0].FormatTok.Tok.getObjCKeywordID()) {
1274 case tok::objc_interface:
1275 case tok::objc_implementation:
1276 case tok::objc_protocol:
1277 Current.Type = TT_ObjCDecl;
Nico Webera2a84952013-01-10 21:30:42 +00001278 break;
1279 case tok::objc_property:
1280 Current.Type = TT_ObjCProperty;
1281 break;
Nico Weber2bb00742013-01-10 19:19:14 +00001282 default:
1283 break;
1284 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001285 }
1286 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001287
1288 if (!Current.Children.empty())
1289 determineTokenTypes(Current.Children[0], IsRHS);
Daniel Jasperf7935112012-12-03 18:12:45 +00001290 }
1291
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001292 bool isBinaryOperator(const AnnotatedToken &Tok) {
Daniel Jasper050948a52012-12-21 17:58:39 +00001293 // Comma is a binary operator, but does not behave as such wrt. formatting.
Daniel Jasper2eda23e2012-12-24 13:43:52 +00001294 return getPrecedence(Tok) > prec::Comma;
Daniel Jasperf7935112012-12-03 18:12:45 +00001295 }
1296
Daniel Jasper71945272013-01-15 14:27:39 +00001297 /// \brief Returns the previous token ignoring comments.
1298 const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
1299 const AnnotatedToken *PrevToken = Tok.Parent;
1300 while (PrevToken != NULL && PrevToken->is(tok::comment))
1301 PrevToken = PrevToken->Parent;
1302 return PrevToken;
1303 }
1304
1305 /// \brief Returns the next token ignoring comments.
1306 const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
1307 if (Tok.Children.empty())
1308 return NULL;
1309 const AnnotatedToken *NextToken = &Tok.Children[0];
1310 while (NextToken->is(tok::comment)) {
1311 if (NextToken->Children.empty())
1312 return NULL;
1313 NextToken = &NextToken->Children[0];
1314 }
1315 return NextToken;
1316 }
1317
1318 /// \brief Return the type of the given token assuming it is * or &.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001319 TokenType determineStarAmpUsage(const AnnotatedToken &Tok, bool IsRHS) {
Daniel Jasper71945272013-01-15 14:27:39 +00001320 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1321 if (PrevToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001322 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001323
1324 const AnnotatedToken *NextToken = getNextToken(Tok);
1325 if (NextToken == NULL)
Daniel Jasperda16db32013-01-07 10:48:50 +00001326 return TT_Unknown;
Daniel Jasperf7935112012-12-03 18:12:45 +00001327
Daniel Jasper71945272013-01-15 14:27:39 +00001328 if (PrevToken->is(tok::l_paren) || PrevToken->is(tok::l_square) ||
1329 PrevToken->is(tok::l_brace) || PrevToken->is(tok::comma) ||
1330 PrevToken->is(tok::kw_return) || PrevToken->is(tok::colon) ||
1331 PrevToken->Type == TT_BinaryOperator ||
Daniel Jaspera1dc93a2013-01-16 16:04:06 +00001332 PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
Daniel Jasperda16db32013-01-07 10:48:50 +00001333 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001334
Daniel Jasper71945272013-01-15 14:27:39 +00001335 if (PrevToken->FormatTok.Tok.isLiteral() || PrevToken->is(tok::r_paren) ||
1336 PrevToken->is(tok::r_square) || NextToken->FormatTok.Tok.isLiteral() ||
1337 NextToken->is(tok::plus) || NextToken->is(tok::minus) ||
1338 NextToken->is(tok::plusplus) || NextToken->is(tok::minusminus) ||
1339 NextToken->is(tok::tilde) || NextToken->is(tok::exclaim) ||
1340 NextToken->is(tok::l_paren) || NextToken->is(tok::l_square) ||
1341 NextToken->is(tok::kw_alignof) || NextToken->is(tok::kw_sizeof))
Daniel Jasperda16db32013-01-07 10:48:50 +00001342 return TT_BinaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001343
Daniel Jasper71945272013-01-15 14:27:39 +00001344 if (NextToken->is(tok::comma) || NextToken->is(tok::r_paren) ||
1345 NextToken->is(tok::greater))
Daniel Jasperda16db32013-01-07 10:48:50 +00001346 return TT_PointerOrReference;
Daniel Jasper542de162013-01-02 15:46:59 +00001347
Daniel Jasper426702d2012-12-05 07:51:39 +00001348 // It is very unlikely that we are going to find a pointer or reference type
1349 // definition on the RHS of an assignment.
Nico Weber6f372e62012-12-23 01:07:46 +00001350 if (IsRHS)
Daniel Jasperda16db32013-01-07 10:48:50 +00001351 return TT_BinaryOperator;
Daniel Jasper426702d2012-12-05 07:51:39 +00001352
Daniel Jasperda16db32013-01-07 10:48:50 +00001353 return TT_PointerOrReference;
Daniel Jasperf7935112012-12-03 18:12:45 +00001354 }
1355
Daniel Jasperfb3f2482013-01-09 08:36:49 +00001356 TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001357 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1358 if (PrevToken == NULL)
1359 return TT_UnaryOperator;
1360
Daniel Jasper8dd40472012-12-21 09:41:31 +00001361 // Use heuristics to recognize unary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001362 if (PrevToken->is(tok::equal) || PrevToken->is(tok::l_paren) ||
1363 PrevToken->is(tok::comma) || PrevToken->is(tok::l_square) ||
1364 PrevToken->is(tok::question) || PrevToken->is(tok::colon) ||
1365 PrevToken->is(tok::kw_return) || PrevToken->is(tok::kw_case) ||
1366 PrevToken->is(tok::at) || PrevToken->is(tok::l_brace))
Daniel Jasperda16db32013-01-07 10:48:50 +00001367 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001368
1369 // There can't be to consecutive binary operators.
Daniel Jasper71945272013-01-15 14:27:39 +00001370 if (PrevToken->Type == TT_BinaryOperator)
Daniel Jasperda16db32013-01-07 10:48:50 +00001371 return TT_UnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001372
1373 // Fall back to marking the token as binary operator.
Daniel Jasperda16db32013-01-07 10:48:50 +00001374 return TT_BinaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001375 }
1376
1377 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001378 TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
Daniel Jasper71945272013-01-15 14:27:39 +00001379 const AnnotatedToken *PrevToken = getPreviousToken(Tok);
1380 if (PrevToken == NULL)
Daniel Jasper13f23e12013-01-14 12:18:19 +00001381 return TT_UnaryOperator;
Daniel Jasper71945272013-01-15 14:27:39 +00001382 if (PrevToken->is(tok::r_paren) || PrevToken->is(tok::r_square) ||
1383 PrevToken->is(tok::identifier))
Daniel Jasperda16db32013-01-07 10:48:50 +00001384 return TT_TrailingUnaryOperator;
Daniel Jasper8dd40472012-12-21 09:41:31 +00001385
Daniel Jasperda16db32013-01-07 10:48:50 +00001386 return TT_UnaryOperator;
Daniel Jasperf7935112012-12-03 18:12:45 +00001387 }
1388
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001389 bool spaceRequiredBetween(const AnnotatedToken &Left,
1390 const AnnotatedToken &Right) {
Daniel Jasper4f397152013-01-08 16:17:54 +00001391 if (Right.is(tok::hashhash))
1392 return Left.is(tok::hash);
1393 if (Left.is(tok::hashhash) || Left.is(tok::hash))
1394 return Right.is(tok::hash);
Daniel Jaspera4396862012-12-10 18:59:13 +00001395 if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma))
1396 return false;
Nico Webera6087752013-01-10 20:12:55 +00001397 if (Right.is(tok::less) &&
1398 (Left.is(tok::kw_template) ||
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001399 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
Daniel Jasperf7935112012-12-03 18:12:45 +00001400 return true;
1401 if (Left.is(tok::arrow) || Right.is(tok::arrow))
1402 return false;
1403 if (Left.is(tok::exclaim) || Left.is(tok::tilde))
1404 return false;
Nico Weber77aa2502013-01-08 19:40:21 +00001405 if (Left.is(tok::at) &&
1406 (Right.is(tok::identifier) || Right.is(tok::string_literal) ||
1407 Right.is(tok::char_constant) || Right.is(tok::numeric_constant) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001408 Right.is(tok::l_paren) || Right.is(tok::l_brace) ||
1409 Right.is(tok::kw_true) || Right.is(tok::kw_false)))
Fariborz Jahanian68a542a2012-12-20 19:54:13 +00001410 return false;
Daniel Jasper736c14f2013-01-16 07:19:28 +00001411 if (Left.is(tok::coloncolon))
1412 return false;
1413 if (Right.is(tok::coloncolon))
1414 return Left.isNot(tok::identifier) && Left.isNot(tok::greater);
Daniel Jasperf7935112012-12-03 18:12:45 +00001415 if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less))
1416 return false;
Daniel Jasper27234032012-12-07 09:52:15 +00001417 if (Right.is(tok::amp) || Right.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001418 return Left.FormatTok.Tok.isLiteral() ||
Daniel Jasper8fbd9682012-12-24 16:51:15 +00001419 (Left.isNot(tok::star) && Left.isNot(tok::amp) &&
1420 !Style.PointerAndReferenceBindToType);
Daniel Jasperf7935112012-12-03 18:12:45 +00001421 if (Left.is(tok::amp) || Left.is(tok::star))
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001422 return Right.FormatTok.Tok.isLiteral() ||
1423 Style.PointerAndReferenceBindToType;
Daniel Jasperf7935112012-12-03 18:12:45 +00001424 if (Right.is(tok::star) && Left.is(tok::l_paren))
1425 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001426 if (Left.is(tok::l_square) || Right.is(tok::r_square))
1427 return false;
1428 if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
Daniel Jasperf7935112012-12-03 18:12:45 +00001429 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001430 if (Left.is(tok::period) || Right.is(tok::period))
1431 return false;
Nico Webera7252d82013-01-12 06:18:40 +00001432 if (Left.is(tok::colon))
1433 return Left.Type != TT_ObjCMethodExpr;
1434 if (Right.is(tok::colon))
1435 return Right.Type != TT_ObjCMethodExpr;
Daniel Jasperf7935112012-12-03 18:12:45 +00001436 if (Left.is(tok::l_paren))
1437 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001438 if (Right.is(tok::l_paren)) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001439 return Line.Type == LT_ObjCDecl || Left.is(tok::kw_if) ||
Nico Weber2bb00742013-01-10 19:19:14 +00001440 Left.is(tok::kw_for) || Left.is(tok::kw_while) ||
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001441 Left.is(tok::kw_switch) || Left.is(tok::kw_return) ||
Daniel Jasperd6a947f2013-01-11 16:09:04 +00001442 Left.is(tok::kw_catch) || Left.is(tok::kw_new) ||
1443 Left.is(tok::kw_delete);
Daniel Jasperf7935112012-12-03 18:12:45 +00001444 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001445 if (Left.is(tok::at) &&
1446 Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
Nico Webere89c42f2013-01-07 16:14:28 +00001447 return false;
Manuel Klimeke7d10a12013-01-10 13:24:24 +00001448 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1449 return false;
Daniel Jasperf7935112012-12-03 18:12:45 +00001450 return true;
1451 }
1452
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001453 bool spaceRequiredBefore(const AnnotatedToken &Tok) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001454 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001455 if (Tok.is(tok::identifier) && !Tok.Children.empty() &&
1456 Tok.Children[0].is(tok::colon) && Tok.Parent->is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001457 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001458 if (Tok.is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001459 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001460 if (Tok.Parent->Type == TT_ObjCMethodSpecifier)
Nico Weber772fbfd2013-01-17 06:14:50 +00001461 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001462 if (Tok.Parent->is(tok::r_paren) && Tok.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001463 // Don't space between ')' and <id>
1464 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001465 if (Tok.Parent->is(tok::colon) && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001466 // Don't space between ':' and '('
1467 return false;
1468 }
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001469 if (Line.Type == LT_ObjCProperty &&
Nico Webera2a84952013-01-10 21:30:42 +00001470 (Tok.is(tok::equal) || Tok.Parent->is(tok::equal)))
1471 return false;
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001472
Daniel Jasper48cb3b92013-01-13 08:19:51 +00001473 if (Tok.Parent->is(tok::comma))
1474 return true;
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001475 if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001476 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001477 if (Tok.Type == TT_OverloadedOperator)
1478 return Tok.is(tok::identifier) || Tok.is(tok::kw_new) ||
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001479 Tok.is(tok::kw_delete) || Tok.is(tok::kw_bool);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001480 if (Tok.Parent->Type == TT_OverloadedOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001481 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001482 if (Tok.is(tok::colon))
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001483 return Line.First.isNot(tok::kw_case) && !Tok.Children.empty() &&
Nico Webera7252d82013-01-12 06:18:40 +00001484 Tok.Type != TT_ObjCMethodExpr;
Daniel Jasper7194e182013-01-10 11:14:08 +00001485 if (Tok.Parent->Type == TT_UnaryOperator ||
1486 Tok.Parent->Type == TT_CastRParen)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001487 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001488 if (Tok.Type == TT_UnaryOperator)
1489 return Tok.Parent->isNot(tok::l_paren) &&
Nico Weber2827a7e2013-01-12 23:48:49 +00001490 Tok.Parent->isNot(tok::l_square) && Tok.Parent->isNot(tok::at) &&
1491 (Tok.Parent->isNot(tok::colon) ||
1492 Tok.Parent->Type != TT_ObjCMethodExpr);
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001493 if (Tok.Parent->is(tok::greater) && Tok.is(tok::greater)) {
1494 return Tok.Type == TT_TemplateCloser && Tok.Parent->Type ==
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001495 TT_TemplateCloser && Style.SplitTemplateClosingGreater;
1496 }
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001497 if (Tok.Type == TT_BinaryOperator || Tok.Parent->Type == TT_BinaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001498 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001499 if (Tok.Parent->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001500 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001501 if (Tok.is(tok::less) && Line.First.is(tok::hash))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001502 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001503 if (Tok.Type == TT_TrailingUnaryOperator)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001504 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001505 return spaceRequiredBetween(*Tok.Parent, Tok);
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001506 }
1507
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001508 bool canBreakBefore(const AnnotatedToken &Right) {
1509 const AnnotatedToken &Left = *Right.Parent;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001510 if (Line.Type == LT_ObjCMethodDecl) {
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001511 if (Right.is(tok::identifier) && !Right.Children.empty() &&
1512 Right.Children[0].is(tok::colon) && Left.is(tok::identifier))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001513 return true;
Nico Weberc7a56342013-01-12 07:00:16 +00001514 if (Right.is(tok::identifier) && Left.is(tok::l_paren) &&
1515 Left.Parent->is(tok::colon))
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001516 // Don't break this identifier as ':' or identifier
1517 // before it will break.
1518 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001519 if (Right.is(tok::colon) && Left.is(tok::identifier) &&
1520 Left.CanBreakBefore)
Daniel Jasperf8673bc2013-01-07 15:36:15 +00001521 // Don't break at ':' if identifier before it can beak.
1522 return false;
1523 }
Nico Webera7252d82013-01-12 06:18:40 +00001524 if (Right.is(tok::colon) && Right.Type == TT_ObjCMethodExpr)
1525 return false;
1526 if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
1527 return true;
Nico Weberc9d73612013-01-12 22:48:47 +00001528 if (isObjCSelectorName(Right))
1529 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001530 if (Left.ClosesTemplateDeclaration)
Daniel Jasper90e51fd2013-01-02 18:30:06 +00001531 return true;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001532 if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
Daniel Jasper66dcb1c2013-01-08 20:03:18 +00001533 Left.Type == TT_UnaryOperator || Right.Type == TT_ConditionalExpr)
Daniel Jasperd1926a32013-01-02 08:44:14 +00001534 return false;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001535 if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
Daniel Jasperda16db32013-01-07 10:48:50 +00001536 return false;
1537
Daniel Jasper11cb81c2013-01-17 12:53:34 +00001538 if (Right.Type == TT_LineComment)
Daniel Jasper942ee722013-01-13 16:10:20 +00001539 // We rely on MustBreakBefore being set correctly here as we should not
1540 // change the "binding" behavior of a comment.
1541 return false;
1542
Daniel Jasperfefb1e62013-01-17 13:31:52 +00001543 // Allow breaking after a trailing 'const', e.g. after a method declaration,
1544 // unless it is follow by ';', '{' or '='.
1545 if (Left.is(tok::kw_const) && Left.Parent != NULL &&
1546 Left.Parent->is(tok::r_paren))
1547 return Right.isNot(tok::l_brace) && Right.isNot(tok::semi) &&
1548 Right.isNot(tok::equal);
1549
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001550 // We only break before r_brace if there was a corresponding break before
1551 // the l_brace, which is tracked by BreakBeforeClosingBrace.
1552 if (Right.is(tok::r_brace))
1553 return false;
1554
Daniel Jasper71945272013-01-15 14:27:39 +00001555 if (Right.is(tok::r_paren) || Right.is(tok::greater))
Daniel Jasperf7935112012-12-03 18:12:45 +00001556 return false;
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001557 return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
1558 Left.is(tok::comma) || Right.is(tok::lessless) ||
1559 Right.is(tok::arrow) || Right.is(tok::period) ||
1560 Right.is(tok::colon) || Left.is(tok::semi) ||
Manuel Klimeka54d1a92013-01-14 16:41:43 +00001561 Left.is(tok::l_brace) || Left.is(tok::question) || Left.Type ==
1562 TT_ConditionalExpr || (Left.is(tok::r_paren) && Left.Type !=
1563 TT_CastRParen && Right.is(tok::identifier)) ||
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001564 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
Daniel Jasperf7935112012-12-03 18:12:45 +00001565 }
1566
Daniel Jasperf7935112012-12-03 18:12:45 +00001567 FormatStyle Style;
1568 SourceManager &SourceMgr;
Manuel Klimekc74d2922013-01-07 08:54:53 +00001569 Lexer &Lex;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001570 AnnotatedLine &Line;
Daniel Jasperf7935112012-12-03 18:12:45 +00001571};
1572
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001573class LexerBasedFormatTokenSource : public FormatTokenSource {
1574public:
1575 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
Daniel Jasper2af6bbe2012-12-18 21:05:13 +00001576 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001577 IdentTable(Lex.getLangOpts()) {
1578 Lex.SetKeepWhitespaceMode(true);
1579 }
1580
1581 virtual FormatToken getNextToken() {
1582 if (GreaterStashed) {
1583 FormatTok.NewlinesBefore = 0;
1584 FormatTok.WhiteSpaceStart =
1585 FormatTok.Tok.getLocation().getLocWithOffset(1);
1586 FormatTok.WhiteSpaceLength = 0;
1587 GreaterStashed = false;
1588 return FormatTok;
1589 }
1590
1591 FormatTok = FormatToken();
1592 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001593 StringRef Text = rawTokenText(FormatTok.Tok);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001594 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
Manuel Klimek52d0fd82013-01-05 22:56:06 +00001595 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
1596 FormatTok.IsFirst = true;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001597
1598 // Consume and record whitespace until we find a significant token.
1599 while (FormatTok.Tok.is(tok::unknown)) {
Manuel Klimeka71e5d82013-01-02 16:30:12 +00001600 FormatTok.NewlinesBefore += Text.count('\n');
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001601 FormatTok.HasUnescapedNewline = Text.count("\\\n") !=
1602 FormatTok.NewlinesBefore;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001603 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
1604
1605 if (FormatTok.Tok.is(tok::eof))
1606 return FormatTok;
1607 Lex.LexFromRawLexer(FormatTok.Tok);
Manuel Klimekef920692013-01-07 07:56:50 +00001608 Text = rawTokenText(FormatTok.Tok);
Manuel Klimek1abf7892013-01-04 23:34:14 +00001609 }
Manuel Klimekef920692013-01-07 07:56:50 +00001610
1611 // Now FormatTok is the next non-whitespace token.
1612 FormatTok.TokenLength = Text.size();
1613
Manuel Klimek1abf7892013-01-04 23:34:14 +00001614 // In case the token starts with escaped newlines, we want to
1615 // take them into account as whitespace - this pattern is quite frequent
1616 // in macro definitions.
1617 // FIXME: What do we want to do with other escaped spaces, and escaped
1618 // spaces or newlines in the middle of tokens?
1619 // FIXME: Add a more explicit test.
1620 unsigned i = 0;
Daniel Jasperda16db32013-01-07 10:48:50 +00001621 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001622 FormatTok.WhiteSpaceLength += 2;
Manuel Klimekef920692013-01-07 07:56:50 +00001623 FormatTok.TokenLength -= 2;
Manuel Klimek1abf7892013-01-04 23:34:14 +00001624 i += 2;
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001625 }
1626
1627 if (FormatTok.Tok.is(tok::raw_identifier)) {
Manuel Klimek1abf7892013-01-04 23:34:14 +00001628 IdentifierInfo &Info = IdentTable.get(Text);
Daniel Jasper050948a52012-12-21 17:58:39 +00001629 FormatTok.Tok.setIdentifierInfo(&Info);
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001630 FormatTok.Tok.setKind(Info.getTokenID());
1631 }
1632
1633 if (FormatTok.Tok.is(tok::greatergreater)) {
1634 FormatTok.Tok.setKind(tok::greater);
1635 GreaterStashed = true;
1636 }
1637
1638 return FormatTok;
1639 }
1640
1641private:
1642 FormatToken FormatTok;
1643 bool GreaterStashed;
1644 Lexer &Lex;
1645 SourceManager &SourceMgr;
1646 IdentifierTable IdentTable;
1647
1648 /// Returns the text of \c FormatTok.
Manuel Klimekef920692013-01-07 07:56:50 +00001649 StringRef rawTokenText(Token &Tok) {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001650 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
1651 Tok.getLength());
1652 }
1653};
1654
Daniel Jasperf7935112012-12-03 18:12:45 +00001655class Formatter : public UnwrappedLineConsumer {
1656public:
Daniel Jasper25837aa2013-01-14 14:14:23 +00001657 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
1658 SourceManager &SourceMgr,
Daniel Jasperf7935112012-12-03 18:12:45 +00001659 const std::vector<CharSourceRange> &Ranges)
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001660 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001661 Whitespaces(SourceMgr), Ranges(Ranges) {}
Daniel Jasperf7935112012-12-03 18:12:45 +00001662
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001663 virtual ~Formatter() {}
Daniel Jasper61bd3a12012-12-04 21:05:31 +00001664
Daniel Jasperf7935112012-12-03 18:12:45 +00001665 tooling::Replacements format() {
Alexander Kornienkoe3276842012-12-07 16:15:44 +00001666 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001667 UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001668 StructuralError = Parser.parse();
Manuel Klimek1abf7892013-01-04 23:34:14 +00001669 unsigned PreviousEndOfLineColumn = 0;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001670 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
1671 TokenAnnotator Annotator(Style, SourceMgr, Lex, AnnotatedLines[i]);
1672 Annotator.annotate();
1673 }
1674 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
1675 E = AnnotatedLines.end();
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001676 I != E; ++I) {
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001677 const AnnotatedLine &TheLine = *I;
1678 if (touchesRanges(TheLine) && TheLine.Type != LT_Invalid) {
1679 unsigned Indent = formatFirstToken(TheLine.First, TheLine.Level,
1680 TheLine.InPPDirective,
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001681 PreviousEndOfLineColumn);
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001682 tryFitMultipleLinesInOne(Indent, I, E);
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001683 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001684 TheLine.First, Whitespaces,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001685 StructuralError);
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001686 PreviousEndOfLineColumn = Formatter.format();
1687 } else {
1688 // If we did not reformat this unwrapped line, the column at the end of
1689 // the last token is unchanged - thus, we can calculate the end of the
1690 // last token, and return the result.
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001691 PreviousEndOfLineColumn =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001692 SourceMgr.getSpellingColumnNumber(
1693 TheLine.Last->FormatTok.Tok.getLocation()) +
1694 Lex.MeasureTokenLength(TheLine.Last->FormatTok.Tok.getLocation(),
1695 SourceMgr, Lex.getLangOpts()) -
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001696 1;
1697 }
1698 }
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001699 return Whitespaces.generateReplacements();
Daniel Jasperf7935112012-12-03 18:12:45 +00001700 }
1701
1702private:
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001703 /// \brief Tries to merge lines into one.
1704 ///
1705 /// This will change \c Line and \c AnnotatedLine to contain the merged line,
1706 /// if possible; note that \c I will be incremented when lines are merged.
1707 ///
1708 /// Returns whether the resulting \c Line can fit in a single line.
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001709 void tryFitMultipleLinesInOne(unsigned Indent,
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001710 std::vector<AnnotatedLine>::iterator &I,
1711 std::vector<AnnotatedLine>::iterator E) {
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001712 unsigned Limit = Style.ColumnLimit - (I->InPPDirective ? 1 : 0) - Indent;
1713
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001714 // We can never merge stuff if there are trailing line comments.
1715 if (I->Last->Type == TT_LineComment)
1716 return;
1717
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001718 // Check whether the UnwrappedLine can be put onto a single line. If
1719 // so, this is bound to be the optimal solution (by definition) and we
1720 // don't need to analyze the entire solution space.
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001721 if (I->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001722 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001723 Limit -= I->Last->TotalLength;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001724
Daniel Jasperd41ee2d2013-01-21 14:18:28 +00001725 if (I + 1 == E || (I + 1)->Type == LT_Invalid)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001726 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001727
Daniel Jasper25837aa2013-01-14 14:14:23 +00001728 if (I->Last->is(tok::l_brace)) {
1729 tryMergeSimpleBlock(I, E, Limit);
1730 } else if (I->First.is(tok::kw_if)) {
1731 tryMergeSimpleIf(I, E, Limit);
Daniel Jasper39825ea2013-01-14 15:40:57 +00001732 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
1733 I->First.FormatTok.IsFirst)) {
1734 tryMergeSimplePPDirective(I, E, Limit);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001735 }
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001736 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001737 }
1738
Daniel Jasper39825ea2013-01-14 15:40:57 +00001739 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
1740 std::vector<AnnotatedLine>::iterator E,
1741 unsigned Limit) {
1742 AnnotatedLine &Line = *I;
Daniel Jasper2ab0d012013-01-14 15:52:06 +00001743 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
1744 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001745 if (I + 2 != E && (I + 2)->InPPDirective &&
1746 !(I + 2)->First.FormatTok.HasUnescapedNewline)
1747 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001748 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jaspera67a8f02013-01-16 10:41:46 +00001749 return;
Daniel Jasper39825ea2013-01-14 15:40:57 +00001750 join(Line, *(++I));
1751 }
1752
Daniel Jasper25837aa2013-01-14 14:14:23 +00001753 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
1754 std::vector<AnnotatedLine>::iterator E,
1755 unsigned Limit) {
Daniel Jasper1b750ed2013-01-14 16:24:39 +00001756 if (!Style.AllowShortIfStatementsOnASingleLine)
1757 return;
Manuel Klimekda087612013-01-18 14:46:43 +00001758 if ((I + 1)->InPPDirective != I->InPPDirective ||
1759 ((I + 1)->InPPDirective &&
1760 (I + 1)->First.FormatTok.HasUnescapedNewline))
1761 return;
Daniel Jasper25837aa2013-01-14 14:14:23 +00001762 AnnotatedLine &Line = *I;
Daniel Jasperc36492b2013-01-16 07:02:34 +00001763 if (Line.Last->isNot(tok::r_paren))
1764 return;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001765 if (1 + (I + 1)->Last->TotalLength > Limit)
Daniel Jasper25837aa2013-01-14 14:14:23 +00001766 return;
1767 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
1768 return;
1769 // Only inline simple if's (no nested if or else).
1770 if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
1771 return;
1772 join(Line, *(++I));
1773 }
1774
1775 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
1776 std::vector<AnnotatedLine>::iterator E,
1777 unsigned Limit){
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001778 // First, check that the current line allows merging. This is the case if
1779 // we're not in a control flow statement and the last token is an opening
1780 // brace.
Daniel Jasper25837aa2013-01-14 14:14:23 +00001781 AnnotatedLine &Line = *I;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001782 bool AllowedTokens =
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001783 Line.First.isNot(tok::kw_if) && Line.First.isNot(tok::kw_while) &&
1784 Line.First.isNot(tok::kw_do) && Line.First.isNot(tok::r_brace) &&
1785 Line.First.isNot(tok::kw_else) && Line.First.isNot(tok::kw_try) &&
1786 Line.First.isNot(tok::kw_catch) && Line.First.isNot(tok::kw_for) &&
Nico Webera21aaae2013-01-11 21:14:08 +00001787 // This gets rid of all ObjC @ keywords and methods.
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001788 Line.First.isNot(tok::at) && Line.First.isNot(tok::minus) &&
1789 Line.First.isNot(tok::plus);
Daniel Jasper25837aa2013-01-14 14:14:23 +00001790 if (!AllowedTokens)
1791 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001792
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001793 AnnotatedToken *Tok = &(I + 1)->First;
1794 if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
1795 !Tok->MustBreakBefore && Tok->TotalLength <= Limit) {
1796 Tok->SpaceRequiredBefore = false;
1797 join(Line, *(I + 1));
1798 I += 1;
1799 } else {
1800 // Check that we still have three lines and they fit into the limit.
1801 if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
1802 !nextTwoLinesFitInto(I, Limit))
Daniel Jasper25837aa2013-01-14 14:14:23 +00001803 return;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001804
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001805 // Second, check that the next line does not contain any braces - if it
1806 // does, readability declines when putting it into a single line.
1807 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
1808 return;
1809 do {
1810 if (Tok->is(tok::l_brace) || Tok->is(tok::r_brace))
1811 return;
1812 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
1813 } while (Tok != NULL);
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001814
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001815 // Last, check that the third line contains a single closing brace.
1816 Tok = &(I + 2)->First;
1817 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
1818 Tok->MustBreakBefore)
1819 return;
1820
1821 join(Line, *(I + 1));
1822 join(Line, *(I + 2));
1823 I += 2;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001824 }
Daniel Jasper25837aa2013-01-14 14:14:23 +00001825 }
1826
1827 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
1828 unsigned Limit) {
Manuel Klimeka4fe1c12013-01-21 16:42:44 +00001829 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
1830 Limit;
Manuel Klimekf4ab9ef2013-01-11 17:54:10 +00001831 }
1832
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001833 void join(AnnotatedLine &A, const AnnotatedLine &B) {
1834 A.Last->Children.push_back(B.First);
1835 while (!A.Last->Children.empty()) {
1836 A.Last->Children[0].Parent = A.Last;
1837 A.Last = &A.Last->Children[0];
1838 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001839 }
1840
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001841 bool touchesRanges(const AnnotatedLine &TheLine) {
1842 const FormatToken *First = &TheLine.First.FormatTok;
1843 const FormatToken *Last = &TheLine.Last->FormatTok;
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001844 CharSourceRange LineRange = CharSourceRange::getTokenRange(
Daniel Jasper7c85fde2013-01-08 14:56:18 +00001845 First->Tok.getLocation(),
1846 Last->Tok.getLocation());
Daniel Jasperf7935112012-12-03 18:12:45 +00001847 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001848 if (!SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(),
1849 Ranges[i].getBegin()) &&
1850 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
1851 LineRange.getBegin()))
1852 return true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001853 }
Manuel Klimek51bd6ec2013-01-10 19:49:59 +00001854 return false;
1855 }
1856
1857 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00001858 AnnotatedLines.push_back(AnnotatedLine(TheLine));
Daniel Jasperf7935112012-12-03 18:12:45 +00001859 }
1860
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001861 /// \brief Add a new line and the required indent before the first Token
1862 /// of the \c UnwrappedLine if there was no structural parsing error.
1863 /// Returns the indent level of the \c UnwrappedLine.
1864 unsigned formatFirstToken(const AnnotatedToken &RootToken, unsigned Level,
1865 bool InPPDirective,
1866 unsigned PreviousEndOfLineColumn) {
Daniel Jasperfd8c4b12013-01-11 14:23:32 +00001867 const FormatToken &Tok = RootToken.FormatTok;
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001868 if (!Tok.WhiteSpaceStart.isValid() || StructuralError)
1869 return SourceMgr.getSpellingColumnNumber(Tok.Tok.getLocation()) - 1;
1870
1871 unsigned Newlines = std::min(Tok.NewlinesBefore,
1872 Style.MaxEmptyLinesToKeep + 1);
1873 if (Newlines == 0 && !Tok.IsFirst)
1874 Newlines = 1;
1875 unsigned Indent = Level * 2;
1876
1877 bool IsAccessModifier = false;
1878 if (RootToken.is(tok::kw_public) || RootToken.is(tok::kw_protected) ||
1879 RootToken.is(tok::kw_private))
1880 IsAccessModifier = true;
1881 else if (RootToken.is(tok::at) && !RootToken.Children.empty() &&
1882 (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) ||
1883 RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) ||
1884 RootToken.Children[0].isObjCAtKeyword(tok::objc_package) ||
1885 RootToken.Children[0].isObjCAtKeyword(tok::objc_private)))
1886 IsAccessModifier = true;
1887
1888 if (IsAccessModifier &&
1889 static_cast<int>(Indent) + Style.AccessModifierOffset >= 0)
1890 Indent += Style.AccessModifierOffset;
1891 if (!InPPDirective || Tok.HasUnescapedNewline) {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001892 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001893 } else {
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001894 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
1895 PreviousEndOfLineColumn, Style);
Manuel Klimek0b689fd2013-01-10 18:45:26 +00001896 }
1897 return Indent;
1898 }
1899
Alexander Kornienko116ba682013-01-14 11:34:14 +00001900 DiagnosticsEngine &Diag;
Daniel Jasperf7935112012-12-03 18:12:45 +00001901 FormatStyle Style;
1902 Lexer &Lex;
1903 SourceManager &SourceMgr;
Daniel Jasperaa701fa2013-01-18 08:44:07 +00001904 WhitespaceManager Whitespaces;
Daniel Jasperf7935112012-12-03 18:12:45 +00001905 std::vector<CharSourceRange> Ranges;
Daniel Jasperf1e4b7d2013-01-14 13:08:07 +00001906 std::vector<AnnotatedLine> AnnotatedLines;
Alexander Kornienko870f9eb2012-12-04 17:27:50 +00001907 bool StructuralError;
Daniel Jasperf7935112012-12-03 18:12:45 +00001908};
1909
1910tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
1911 SourceManager &SourceMgr,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001912 std::vector<CharSourceRange> Ranges,
1913 DiagnosticConsumer *DiagClient) {
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001914 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko116ba682013-01-14 11:34:14 +00001915 OwningPtr<DiagnosticConsumer> DiagPrinter;
1916 if (DiagClient == 0) {
1917 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
1918 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
1919 DiagClient = DiagPrinter.get();
1920 }
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001921 DiagnosticsEngine Diagnostics(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001922 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
Alexander Kornienko116ba682013-01-14 11:34:14 +00001923 DiagClient, false);
Alexander Kornienko5b7157a2013-01-10 15:05:09 +00001924 Diagnostics.setSourceManager(&SourceMgr);
1925 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
Daniel Jasperf7935112012-12-03 18:12:45 +00001926 return formatter.format();
1927}
1928
Daniel Jasperc1fa2812013-01-10 13:08:12 +00001929LangOptions getFormattingLangOpts() {
1930 LangOptions LangOpts;
1931 LangOpts.CPlusPlus = 1;
1932 LangOpts.CPlusPlus11 = 1;
1933 LangOpts.Bool = 1;
1934 LangOpts.ObjC1 = 1;
1935 LangOpts.ObjC2 = 1;
1936 return LangOpts;
1937}
1938
Daniel Jasper8d1832e2013-01-07 13:26:07 +00001939} // namespace format
1940} // namespace clang